Angular 6嵌套FormGroup模板验证 [英] Angular 6 Nested FormGroup Template Validation
问题描述
我的表单组结构如下(order.component.ts):
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]
}),
...
});
在模板(order.component.html)中,我有:
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>
这有效,但是是表达orderForm.controls['customer'].controls['name']
的较短方法吗?例如,* ngIf条件为"name.invalid && (name.dirty || name.touched)"
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)"
推荐答案
是的,这是获取嵌套表单控件的正确方法,并且没有快捷方式.
Yes, that is the correct way to fetch nested form Control and no shortcut.
或者您可以在组件中创建一些属性,这些属性指向orderForm.get('customer')
表单对象
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')
并像{{customerForm.get('name').valid}}
这篇关于Angular 6嵌套FormGroup模板验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!