Angular 6 嵌套 FormGroup 模板验证

问题描述 投票:0回答:3

我的表单组结构如下所示(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)"

会更简洁
angular angular6 angular-template
3个回答
4
投票

我遇到了同样的问题。我的主要问题是使用

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>

3
投票

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

或者您可以在组件中创建一些指向

orderForm.get('customer')
表单对象

的属性
private customerForm : FormGroup

并在表单初始化后分配它

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

然后像

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

一样获取它

0
投票

Angular 16:我遇到了同样的问题,并通过在 .ts 文件中设置标志来解决它。

.ts 文件:

Public customerValid: boolean = true;
onSubmit() {
 this.customerValid = (this.form.controls['customer'] as FormGroup).controls['name'].valid;
 ....
}

.html:

<form [formGroup]="orderForm" (ngSubmit)="onSubmit()">
  <div formGroupName="customer">
    <legend>Customer Information</legend>
    <label for="name">Full name:</label>
    <input type="text"  formControlName="name"
    [ngClass]="{ 'is-invalid': submitted && !customerValid}" />
    <div *ngIf="submitted && !customerValid" class="invalid-feedback">
       <div *ngIf="!customerValid"> Name is required</div>
    </div>
  </div>
</form>
© www.soinside.com 2019 - 2024. All rights reserved.