Angular2 - 在ngFor和被动形式中选中一个框

时间:2017-12-13 18:43:58

标签: javascript angular typescript

我有一个从数据库返回的对象,该数据库是ID的名称列表,以及它们是否被选中。

对象

let data = [{
   AttributeID: 1,
   AttributeName: 'Something',
   IsSelected: 'True'
},
{
   AttributeID: 2,
   AttributeName: 'Something Else',
   IsSelected: 'False'
}]

HTML:

 <div *ngFor="let data of modalData.variableData">
   <input type="checkbox" (change)="onAttributeCheckboxChange(data.AttributeID, $event.target.checked)" [checked]="(data.IsSelected == 'True' ? 1 : 0)"> {{data.AttributeName}}<br>
 </div>

组件:

private settingsForm: FormGroup;

ngOnInit() {
    this.settingsForm = this.fb.group({
        attribute: this.fb.array([])
    });
}


onAttributeCheckboxChange(attribute: number, isChecked: boolean) {
    const attributeFormArray = <FormArray>this.settingsForm.controls.attribute;

    if (isChecked) {
        attributeFormArray.push(new FormControl(attribute));
    } else {
        let index = attributeFormArray.controls.findIndex(x => x.value == attribute)
        attributeFormArray.removeAt(index);
    }
}

我在这里做错了,因为虽然特定的框在我的UI上显示为checked,但当我提交表单时,数组将返回为空。

onSave() {
    console.log(this.settingsForm.value)
}

如何确保form最初检查哪个复选框,而不仅仅是[checked]知道哪些元素本身?

1 个答案:

答案 0 :(得分:1)

您可以在OnInit上检查您的数据,并将选中的数据推送到表单数组,方法与onChange相同:

export class App {
    emails = [{email:"email1", isSelected: 'true'},{email:"email2", isSelected: 'false'},{email:"email3", isSelected: 'true'},{email:'email4', isSelected: 'false'}]
    myForm: FormGroup;

    constructor(private fb: FormBuilder) {
      this.myForm = this.fb.group({
        useremail: this.fb.array([])
      });
    }

    ngOnInit() {
      for(let item of this.emails){
        if (item.isSelected === 'true'){
          this.myForm.controls.useremail.push(new FormControl(item.email));
        }
      }
    }  

    onChange(email:string, isChecked: boolean) {
      const emailFormArray = <FormArray>this.myForm.controls.useremail;

      if(isChecked) {
        emailFormArray.push(new FormControl(email));
      } else {
        let index = emailFormArray.controls.findIndex(x => x.value == email)
        emailFormArray.removeAt(index);
      }
  }

  submitForm(event){
    console.log(this.myForm.value);
  }

}

你有一个有效的助手here