lundi 6 mai 2019

How to fix issue with not being able to read checkbox values from angular form?

I'm trying to show a list of checkboxes and dynamically change that list on runtime. But once the new checkboxes are populated, the form.value has the updated list but not the updated values(based on user selection)

I have been following this article: https://coryrylan.com/blog/creating-a-dynamic-checkbox-list-in-angular

This is my code to add the checkboxes:

private addCheckboxes() {
    const searchControls = (this.form.controls.searchDataControls as FormArray) ;
    while (searchControls.length !== 0) {
      searchControls.removeAt(0);
    }
    this.searchDataResult.map((o, i) => {
      const control = new FormControl();
      searchControls.push(control);
    });
  }

This is my code for submit:

  submitSelection() {
    const selectedData: number[] = this.form.value.searchDataControls
      .map((value: any, index: number) => (value ? this.searchDataResult[index].id : null))
      .filter((value: any) => value !== null);
  }

This works perfectly on first load. But when addCheckboxes is called a second time with new searchDataResult, selectedData is always empty.




Aucun commentaire:

Enregistrer un commentaire