反应式嵌套形式.获取错误无法读取未定义的属性“hasError" [英] Reactive nesting forms. Getting error cannot read property 'hasError' of undefined
问题描述
我使用了 angular 8 的反应嵌套形式和 angular 材料.
在 component.ts 文件中
this.dataForm = this.formBuilder.group({名称:[null,Validators.required],用户:this.formBuilder.group({名字:[null,Validators.required],姓氏:[null,Validators.required]})});获取数据控件(){返回 this.dataForm.controls;}
在 component.html 文件中
</表单>
获取错误无法读取未定义的属性hasError".我试过像
<mat-error *ngIf="dataControls.user.firstname.hasError('required')">需要名字</mat-error>
但是不行
您在 FormGroup 中有一个 FormGroup,因此:
*ngIf="dataControls.user.controls.firstname.hasError('required')"
在打字稿中,您需要进行强制转换(以避免语法错误):
(this.dataControls.user).controls.firstname.hasError('required')
有更好的方法,打字稿方面:
this.dataControls.user.get('firstname').hasError('required');
I used reactive nesting forms of angular 8 with angular material.
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;
}
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>
Getting error cannot read property 'hasError' of undefined. I tried like
<mat-error *ngIf="dataControls.user.firstname.hasError('required')">Firstname required</mat-error>
But not work
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')
EDIT:
There is a better way, typescript side:
this.dataControls.user.get('firstname').hasError('required');
这篇关于反应式嵌套形式.获取错误无法读取未定义的属性“hasError"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!