Angular ReactiveForms: Producing an array of checkbox values?

前端 未结 12 651
执念已碎
执念已碎 2020-11-29 17:16

Given a list of checkboxes bound to the same formControlName, how can I produce an array of checkbox values bound to the formControl, rather than s

12条回答
  •  庸人自扰
    2020-11-29 17:53

    It's significantly easier to do this in Angular 6 than it was in previous versions, even when the checkbox information is populated asynchronously from an API.

    The first thing to realise is that thanks to Angular 6's keyvalue pipe we don't need to have to use FormArray anymore, and can instead nest a FormGroup.

    First, pass FormBuilder into the constructor

    constructor(
        private _formBuilder: FormBuilder,
    ) { }
    

    Then initialise our form.

    ngOnInit() {
    
        this.form = this._formBuilder.group({
            'checkboxes': this._formBuilder.group({}),
        });
    
    }
    

    When our checkbox options data is available, iterate it and we can push it directly into the nested FormGroup as a named FormControl, without having to rely on number indexed lookup arrays.

    const checkboxes = this.form.get('checkboxes');
    options.forEach((option: any) => {
        checkboxes.addControl(option.title, new FormControl(true));
    });
    

    Finally, in the template we just need to iterate the keyvalue of the checkboxes: no additional let index = i, and the checkboxes will automatically be in alphabetical order: much cleaner.

    Options

提交回复
热议问题