gpt4 book ai didi

Angular 6 嵌套 FormGroup 模板验证

转载 作者:太空狗 更新时间:2023-10-29 18:23:13 25 4
gpt4 key购买 nike

我的表单组结构如下所示 (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'] 时失败并出现错误:

Property 'controls' does not exist on type '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>

关于Angular 6 嵌套 FormGroup 模板验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51459573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com