Angular 2: Iterate over reactive form controls

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

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

相关标签:
9条回答
  • 2020-12-02 07:32

    I create this function to make it* I have a control with name 'order', and pass index to him.

    {"conditionGroups": [
       {
         "order": null,
         "conditions": []
       }
      ]
    }
    
    
    updateFormData() {
        const control = <FormArray>this.form.controls['conditionGroups'];  
        control.value.map((x,index)=>{
        x.order = index; 
     })
    
    0 讨论(0)
  • 2020-12-02 07:33

    Seems that get function is not working anymore for retrieving specific values in your form in Angular 8, so this is how I solved it based on the answer of @Liviu Ilea.

    for (const field in this.myForm.controls) { // 'field' is a string
      console.log(this.myForm.controls[field].value);
    }
    
    0 讨论(0)
  • 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();
            }
        });
    }
    
    0 讨论(0)
  • 2020-12-02 07:42

    Using @Marcos answer I created a function that can be called passing a formGroup as parameter and it marks every formGroup children controls to dirty, just to make it usable from more places around the code putting it inside a service, for example.

    public touchAllFormFields(formGroup: FormGroup): void {
        Object.keys(formGroup.controls).forEach((key) => {
            formGroup.get(key).markAsDirty();
        });
    }
    

    hope it helps ;)

    0 讨论(0)
  • 2020-12-02 07:47

    Found out that Object.keys can handle this..

        Object.keys(this.form.controls).forEach(key => {
          this.form.get(key).markAsDirty();
        });
    

    For Angular 8+, use the following (based on Michelangelo answer):

        Object.keys(this.form.controls).forEach(key => {
          this.form.controls[key].markAsDirty();
        });
    
    0 讨论(0)
  • 2020-12-02 07:50

    For what it's worth, there's another way to do this without having to use Object.keys(...) magic:

    for (const field in this.form.controls) { // 'field' is a string
    
      const control = this.form.get(field); // 'control' is a FormControl  
    
    }
    
    0 讨论(0)
提交回复
热议问题