Search code examples
angularformbuilderangular-reactive-forms

Accessing nested FormBuilder Angular6


i have a simple reactive form

this.orderForm = this._formBuilder.group({
    metadataFormGroup: this._formBuilder.group({
      data1: ['', [Validators.pattern(this.nserRegex)]],
      data2: ['', [Validators.pattern(this.crqRegex)]]
    }),

    infoFormGroup: this._formBuilder.group({
      data3: ['', [Validators.pattern(this.blcRegex)]],
      data4: new FormControl([])
    })
  });

I am trying to access the

this.orderForm['metadataFormGroup'].controls['data1'].setValue('11111111')

But it is giving erro that ERROR TypeError: "this.orderForm.metadataFormGroup is undefined"

Please help


Solution

  • Try like this by using get method

    this.orderForm.get('metadataFormGroup').get('data1').setValue('11111111');
    

    The line above can be simplfy by using get property

    
    get  metadataFormGroup(){
      return this.orderForm.get('metadataFormGroup');
    }
    
    

    Then you can set the value like this

    this.metadataFormGroup.get('data1').setValue('11111111');