formGroup.get vs formGroup.controls in reactive form - Angular

前端 未结 2 924
抹茶落季
抹茶落季 2020-12-08 18:46

Is there any preferred way when selecting validation using

  • myForm.controls[\'name\'].valid
  • myForm.get(\'name\').valid
  • <
2条回答
  •  情歌与酒
    2020-12-08 19:52

    Just like what you have found, FormGroup.get is designed to access target formcontrol by it's path. And it's more often used for complicated(multi layer embed) situation, which makes it easy to get the target control from multi layer embed form and also makes code clear and easily to understand.

    Take below as a example, you can simply access the first element of the embed FormArray by this.form.get('test.0') instead of this.form.controls.test.controls[0]:

    this.form = this.formBuilder.group(
      {
        test: this.formBuilder.array(
          [
            ['form control 1 in form array'],
            ['form control 1 in form array'],
            ...
          ]
        )
      }
    );
    

提交回复
热议问题