Angular 6 嵌套 FormGroup 模板验证 [英] Angular 6 Nested FormGroup Template Validation

查看:32
本文介绍了Angular 6 嵌套 FormGroup 模板验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

我遇到了同样的问题.我的主要问题是 ng build --prod 在使用 orderForm.controls['customer'].controls['name'] 时失败,错误:

I ran into same issue. My main problem was that ng build --prod fails when using orderForm.controls['customer'].controls['name'] with error:

AbstractControl"类型上不存在属性controls".

Property 'controls' does not exist on type 'AbstractControl'.

显然这只是模板编译为 TS 时的类型问题.

Apparently this is just type issue when template gets compiled to TS.

我的方法是为嵌套表单组创建 getter 并转换正确的类型来解决我和你的问题:

My approach is to create getter for nested form group and cast the correct type which solves both my issue and yours:

get customer() {
  return this.orderForm.controls.customer as FormGroup;
}

在 HTML 中使用:

used in 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 模板验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆