Angular 6 Nested FormGroup Template Validation

一曲冷凌霜 提交于 2019-12-23 19:14:54

问题


My form group structure looks like this (order.component.ts):

this.orderForm = this.formBuilder.group({
  customer: this.formBuilder.group({
    name: ['', Validators.required],
    phone: ['', Validators.required],
    email: ['', Validators.required]
  }),
  ...
});

In the template (order.component.html) I have:

<form [formGroup]="orderForm" (ngSubmit)="onSubmit()">
  <fieldset formGroupName="customer">
    <legend>Customer Information</legend>
    <label for="name">Full name:</label>
    <input type="text" formControlName="name" class="form-control" name="name" id="name" required>
    <small class="form-text text-danger" *ngIf="orderForm.controls['customer'].controls['name'].invalid && (orderForm.controls['customer'].controls['name'].dirty || orderForm.controls['customer'].controls['name'].touched)">Name invalid</small>
  </fieldset>
  ...
</form>

This works, but is a shorter way of expressing orderForm.controls['customer'].controls['name']? For example it would be more succinct for the *ngIf condition to be "name.invalid && (name.dirty || name.touched)"


回答1:


Yes, that is the correct way to fetch nested form Control and no shortcut.

or you could create some property in your component which points to orderForm.get('customer') form object

private customerForm : FormGroup

And assign it after form initialization

this.customerForm = this.orderForm.get('customer')

and fetch it like {{customerForm.get('name').valid}}




回答2:


I ran into same issue. My main problem was that ng build --prod fails when using orderForm.controls['customer'].controls['name'] with error:

Property 'controls' does not exist on type 'AbstractControl'.

Apparently this is just type issue when template gets compiled to TS.

My approach is to create getter for nested form group and cast the correct type which solves both my issue and yours:

get customer() {
  return this.orderForm.controls.customer as FormGroup;
}

used in HTML:

<small class="form-text text-danger" *ngIf="customer.controls['name'].invalid && (customer.controls['name'].dirty || customer.controls['name'].touched)">Name invalid</small>


来源:https://stackoverflow.com/questions/51459573/angular-6-nested-formgroup-template-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!