Angular forms - accessing nested controls in a template

I have a built-in control group inside my form and I want to access their form state state (for example, pristine and valid) to dynamically display validation errors.

Dynamically built this way

controlMap['password'] = this.password;
controlMap['customData'] = this.formBuilder.group(customDataControlMap);
this.form = new FormGroup(controlMap)

      

from obj like

{
  controls:{
    password:{} 
    --->nested 
    customData:{
       controls:{
          customerId:{}
       }
    }
  }
}

      

ngClass in the template looks pretty ugly

[ngClass]="( !form.controls.customData.controls.customerId.valid && !form.controls.customData.controls.customerId.touched && submitted) ? 'invalid' : ''"

      

and won't work when i try to build it (ng build -prod)

ERROR in ng: ///Users/hanche/Desktop/Development/selfbits/beratergruppe-leistungen-webclient/src/app/pages/clients/client-new/client-new.component.html (6,61): Rule y 'controls' does not exist on type 'AbstractControl'.

+3


source to share


1 answer


try it

form.get('customData').get('customerId')?.invalid

      

or

form.get('customData.customerId')

      

Is there a way to avoid calling functions in the template?



using getter

class YourComponent {
  get dataCustomerId() {
    return this.form.get('customData.customerId');
  }
}

      

template:

[ngClass]="dataCustomerId?.invalid"

      

angular forms - accessing nested controls in a template

+3


source







All Articles