我的表单组结构如下(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)"
会更简洁
我遇到了同样的问题。我的主要问题是ng build --prod
在使用orderForm.controls['customer'].controls['name']
时失败,并出现错误:
显然,当模板编译到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>
是的,这是获取嵌套表单控件的正确方法,没有快捷方式。
或者你可以在你的组件中创建一些指向orderForm.get('customer')
表单对象的属性
private customerForm : FormGroup
并在表单初始化后分配
this.customerForm = this.orderForm.get('customer')
并像{{customerForm.get('name').valid}}
一样获取