问题描述
我正在使用 Angular Material 并尝试显示错误。问题是我无法连接到实际值。
这是我的 component.ts 代码:
myForm!: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm= this.fb.group({
users: this.fb.array([])
});
}
//getting users as a form arr
get Users(){
return this.myForm.get('users') as FormArray;
}
//adding new dynamic forms
addUser(){
const user = this.fb.group({
fname: [null,Validators.required],lname: ['',updateOn: 'blur'
})
this.Users.push(user);
}
这是我的 html 模板:
<div *ngFor="let user of Users.controls; let i = index" [formGroupName]="i">
<mat-form-field>
<input matInput placeholder="first name" formControlName="fname">
<mat-error *ngIf="user['controls'].fname.hasError('required')">
Enter the first name
</mat-error>
</mat-form-field>
</div>
get User() {
return (this.myForm.controls.users as FormGroup).controls;
}
然后尝试用 html 编写:
*ngIf="user['User'].fname.hasError('required')"
它仍然显示此错误:错误 TS7052:元素隐式具有 'any' 类型,因为类型 'AbstractControl' 没有索引签名。您的意思是调用“获取”吗?
如何绑定到这些值?
解决方法
您在 mat-error 上写的条件是错误的。应该是这样的:
<div [formGroup]="myForm">
<div formArrayName="users">
<div *ngFor="let user of Users.controls; let i = index" [formGroupName]="i">
<mat-form-field>
<input matInput placeholder="first name" formControlName="fname">
<mat-error *ngIf="user?.get('fname')?.errors">
Enter the first name
</mat-error>
</mat-form-field>
</div>
</div>
</div>