我正在使用Angular Material并尝试显示错误。问题是我无法连接到实际值。
这是我的组件。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: ['', Validators.required],
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函数,但结果是这样的:
get User() {
return (this.myForm.controls.users as FormGroup).controls;
}
然后尝试用html编写,比如:
*ngIf="user['User'].fname.hasError('required')"
它仍然显示此错误:错误TS7052:元素隐式具有"any"类型,因为类型"AbstractControl"没有索引签名。你是想叫"get"吗
我如何绑定到这些值?
您已经在mat上写入了条件错误。应如下所示:
<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>