简体   繁体   中英

Angular2 - Check a box within an ngFor and reactive form

I have an object that is being returned from a database which is a list of names their ID's, and whether or not they are selected.

Object:

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>

Component:

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);
    }
}

I am doing something wrong here because although the specific box's are displaying as checked on my UI, when I submit the form, the array is coming back as empty.

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

How can I ensure that the form knows which checkbox's are initially checked and not just the elements themselves via [checked] ?

You can do a check of your data on OnInit and push the checked ones to the form array the same way is done on 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);
  }

}

You have a working plunkr here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM