反应性嵌套形式.获取错误无法读取未定义的属性"hasError" [英] Reactive nesting forms. Getting error cannot read property 'hasError' of undefined

查看:90
本文介绍了反应性嵌套形式.获取错误无法读取未定义的属性"hasError"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将角8的反应嵌套形式与角材料一起使用.

I used reactive nesting forms of angular 8 with angular material.

在component.ts文件中

in component.ts file

this.dataForm = this.formBuilder.group({
     name: [null, Validators.required],
     user: this.formBuilder.group({ 
        firstname: [null, Validators.required],
        lastname: [null, Validators.required]
     })
});

get dataControls() {
  return this.dataForm.controls;
}

在component.html文件中

In component.html file

<form [formGroup]="dataForm">
  <mat-form-field>
     <mat-label>Name</mat-label>
     <input matInput type="text" formControlName="name" required>
     <mat-error *ngIf="dataControls.name.hasError('required')">Name required</mat-error>
  </mat-form-field>
  <div formGroupName="user">
  <mat-form-field>
     <mat-label>First Name</mat-label>
     <input matInput type="text" formControlName="firstname" required>
     <mat-error *ngIf="dataControls.firstname.hasError('required')">Firstname required</mat-error>
  </mat-form-field>
  <mat-form-field>
     <mat-label>Last Name</mat-label>
     <input matInput type="text" formControlName="lastname" required>
     <mat-error *ngIf="dataControls.lastname.hasError('required')">Lastname required</mat-error>
  </mat-form-field>
  </div>
</form>

获取错误无法读取未定义的属性"hasError".我尝试过

Getting error cannot read property 'hasError' of undefined. I tried like

<mat-error *ngIf="dataControls.user.firstname.hasError('required')">Firstname required</mat-error>

但是不行

推荐答案

您在FormGroup中有一个FormGroup,因此:

You have a FormGroup in a FormGroup so:

*ngIf="dataControls.user.controls.firstname.hasError('required')"

在打字稿中,您需要进行强制转换(以避免语法错误):

In typescript, you will need to cast (to avoid syntax error) :

(<FormGroup>this.dataControls.user).controls.firstname.hasError('required') 

还有更好的方法,打字稿方面:

There is a better way, typescript side:

this.dataControls.user.get('firstname').hasError('required');

这篇关于反应性嵌套形式.获取错误无法读取未定义的属性"hasError"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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