5

I'm using Angular 7

I have a nested reactive form

this.salonProfileForm = this.fb.group({
  salonName: new FormControl('', [Validators.required]),
  address: this.fb.group({
    city: new FormControl('', [Validators.required])
  })
});

get f() {
    return this.salonProfileForm.controls;
}

And I have the HTML form like

<input type="text" formControlName="salonName" required />
<ng-container *ngIf="submitted && f.salonName.invalid && (f.salonName.dirty || f.salonName.touched)">
   <small *ngIf="f.salonName.errors.required">
      Salon name is required
   </small>
</ng-container>

<div formGroupName="address">
  <input type="text" formControlName="city" />
  <ng-container *ngIf="submitted && f.city.invalid && (f.city.dirty || f.city.touched)">
    <small *ngIf="f.city.errors.required">
        city is required
    </small>
  </ng-container>
</div>

But this gives error on city input ng-container field as

ERROR TypeError: Cannot read property 'invalid' of undefined

How can I validate the nested input fields?

console.log(this.f.address)

enter image description here

0

1 Answer 1

5

You have to access like following:

f.address.controls.city.invalid

Edit

export class Home implements OnInit {
  salonProfileForm : FormGroup;

  ngOnInit() {
    this.salonProfileForm = new FormGroup({
      'salonName': new FormControl('', [Validators.required]),
      'address': new FormGroup({
        'city': new FormControl('', [Validators.required])
    })
  });
 }

}

Moving to .html template

<form [formGroup]="salonProfileForm " (ngSubmit)="onSubmit()">

<div formGroupName="address">
  <input type="text" formControlName="city" />
  <ng-container *ngIf="!salonProfileForm.get('address.city').valid && salonProfileForm.get('address.city').touched">
    <span>This is required</span>
  </ng-container>
</div>

</form>

I have pasted in shape it works , So feel free to update your code to fit the above.

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

6 Comments

Still gives the same error. Also the webstorm editor gives unresolved variable city error.
Kindly console.log(f.address) and show me the output
Hey, While running the command ng build --prod, it gives error ` Property 'controls' does not exist on type 'AbstractControl'.` on the line where I have the above error check.
stackblitz.com/edit/angular-rq8z9j Check this for the html and ts content
@AnujTBE Try to add a different question for the last error you get maybe it's not related to this answer
|

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.