Angular 2: Iterate over reactive form controls

前端 未结 9 768
遥遥无期
遥遥无期 2020-12-02 07:23

I would like to markAsDirty all the controls inside of a FormGroup.

9条回答
  •  不知归路
    2020-12-02 07:40

    The accepted answer is correct for a flat form structure, but does not completely answer the original question. A web page may require nested FormGroups and FormArrays, and we must account for this to create a robust solution.

    public markControlsDirty(group: FormGroup | FormArray): void {
        Object.keys(group.controls).forEach((key: string) => {
            const abstractControl = group.controls[key];
    
            if (abstractControl instanceof FormGroup || abstractControl instanceof FormArray) {
                this.markControlsDirty(abstractControl);
            } else {
                abstractControl.markAsDirty();
            }
        });
    }
    

提交回复
热议问题