0

I'm trying to create a multi-select checkbox list in a form using reactive forms but am running into an issue where the FormArray I create to store the selected checkbox values isn't resetting with the rest of the form on submission. This is resulting in an array with multiple null values corresponding to previous submissions.

the relevant html code:


<form [formGroup]="dieSetForm" (ngSubmit)="submitForm()" novalidate>
<label>Die Types:
        <div *ngFor="let dieType of dieTypes; let i = index">
            <label for="dieType{{dieType}}">
                <input 
                id="dieType{{dieType}}" 
                type="checkbox" name="dieType" 
                [value] = "dieType.value" 
                (change)="onCheckboxChange($event)">
                {{dieType.name}}
                </label>
        </div>
        </label>
        <input type="submit" value="Submit">
    </form>



and the relevant part of the component.ts file:



    export class CreateDieSetComponent implements OnInit {
  
  dieSetForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.dieSetForm = this.fb.group({
      dieTypesCheck: this.fb.array([]),
      name: new FormControl('')
    })
  }


  dieTypes: Array<any> = [
    { name: '4', value: '4'},
    { name: '6', value: '6'},
    { name: '8', value: '8'},
    { name: '10', value: '10'},
    { name: '12', value: '12'},
    { name: '20', value: '20'}
  ];

  onCheckboxChange(e) {
    const dieTypesCheck: FormArray = this.dieSetForm.get('dieTypesCheck') as FormArray;

    if (e.target.checked) {
      dieTypesCheck.push(new FormControl(e.target.value));
    } else {
      let i: number = 0;
      dieTypesCheck.controls.forEach((item: FormControl) => {
        if (item.value == e.target.value) {
          dieTypesCheck.removeAt(i);
          return;
        }
        i++;
      });
    }
  }

  submitForm() {
    console.log(this.dieSetForm.value.name);
    console.log(this.dieSetForm.value.dieTypesCheck);
    this.dieSetForm.reset();
  }

  ngOnInit() {
  }
}

1 Answers1

0

Form arrays need to be emptied manually, resetting just resets the controls inside them, you’ll have to add something like:

(this.dieSetForm.get('dieTypesCheck') as FormArray).clear();

Right before you call reset on the group if you want to remove all of the controls as well.

bryan60
  • 28,215
  • 4
  • 48
  • 65