5

I have a nested control group inside my form and i want to access their form state value (like pristine and valid) to display validation errors dynamically.

The is dynamically built like this

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

the from obj is like

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

the ngClass in the template it looks quite ugly

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

and won't work in 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): Propert y 'controls' does not exist on type 'AbstractControl'.

1
  • any plunked or html how the above hierarchy is composed? trying to achieve something similar, but the get(...) does not work as expected... Commented Mar 21, 2018 at 15:18

1 Answer 1

10

try this

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

or

form.get('customData.customerId')

is there a way to avoid function calls in template?

using getter

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

template:

[ngClass]="dataCustomerId?.invalid"

angular forms - accessing nested controls in template

Sign up to request clarification or add additional context in comments.

3 Comments

What about form.get('customData.customerId')? :)
thanks that works, but is there a way to avoid function calls in template?
@HanChe you could create getter in your component

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.