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
  • you has no input to control the FormArray :( Commented Aug 31, 2020 at 15:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much, this worked! This is my first time using form arrays so i learned something new.
np, don't forget to mark and upvote people who help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.