How can I bind a list of checkboxes in a form using Angular?

前端 未结 2 940
执念已碎
执念已碎 2021-01-26 18:10

I have a form that contains a list of checkboxes for the user to check and then when the user submit the form, it should submit the list of checkboxes as an array of objects. In

2条回答
  •  孤独总比滥情好
    2021-01-26 18:42

    You have done all except form initialization

    myForm: FormGroup = this.initModelForm();
    

    Full code is: I am console logging the formArray value

    import { Component } from '@angular/core';
    import { FormGroup, FormArray, FormControl, FormBuilder } from '@angular/forms';
    
    export interface Fruit {
      uid: string;
      name: string;
    }
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent   {
    public checks = [
      {description: 'descr1', value: 'value1'},
      {description: "descr2", value: 'value2'},
      {description: "descr3", value: 'value3'}
    ];
    
    myForm: FormGroup = this.initModelForm();
    
    constructor(
      public _fb: FormBuilder
    ) { }
    
    initModelForm(): FormGroup{
      return this._fb.group({
        otherControls: [''],
        myChoices: new FormArray([])
      })
    }
    
    onCheckChange(event) {
      console.log(event);
      const formArray: FormArray = this.myForm.get('myChoices') as FormArray;
    
      /* Selected */
      if(event.target.checked){
        // Add a new control in the arrayForm
        formArray.push(new FormControl(event.target.value));
      }
      /* unselected */
      else{
        // find the unselected element
        let i: number = 0;
    
        formArray.controls.forEach((ctrl: FormControl) => {
          if(ctrl.value == event.target.value) {
            // Remove the unselected element from the arrayForm
            formArray.removeAt(i);
            return;
          }
    
          i++;
        });
      }
      console.log(formArray.value);
    }
    }
    

提交回复
热议问题