Angular 6嵌套FormGroup模板验证

时间:2018-07-21 19:50:00

标签: angular angular6 angular-template

我的表单组结构如下(order.component.ts):

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

在模板(order.component.html)中,我有:

<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>

这有效,但是是表达orderForm.controls['customer'].controls['name']的较短方法吗?例如,将* ngIf条件设为"name.invalid && (name.dirty || name.touched)"

会更简洁

2 个答案:

答案 0 :(得分:2)

是的,这是获取嵌套表单控件且没有快捷方式的正确方法。

或者您可以在组件中创建一些属性,这些属性指向orderForm.get('customer')表单对象

private customerForm : FormGroup

并在表单初始化后分配

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

并像{{customerForm.get('name').valid}}

一样获取

答案 1 :(得分:0)

我遇到了同样的问题。我的主要问题是,ng build --prod在使用orderForm.controls['customer'].controls['name']时出现错误:

  

类型“ AbstractControl”上不存在属性“控件”。

当模板被编译为TS时,显然这只是类型问题。

我的方法是为嵌套表单组创建getter并转换正确的类型,从而解决我和你的问题:

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

用于HTML:

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