我的表单组结构如下所示(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']
有错误:
“AbstractControl”类型上不存在属性“controls”。
显然这只是模板编译为 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)