动态表单中的角度验证 [英] Angular validation within dynamic forms
问题描述
我正在使用 Angular Material 并尝试显示错误.问题是我无法连接到实际值.
这是我的 component.ts 代码:
myForm!: FormGroup;构造函数(私人FB:FormBuilder){}ngOnInit() {this.myForm= this.fb.group({用户:this.fb.array([])});}//以表格形式获取用户 arr获取用户(){返回 this.myForm.get('users') 作为 FormArray;}//添加新的动态表单添加用户(){const 用户 = this.fb.group({fname: [null, Validators.required],lname: ['', Validators.required],更新:'模糊'})this.Users.push(user);}
这是我的 html 模板:
<mat-form-field><input matInput placeholder="名字"formControlName=fname"><mat-error *ngIf="user['controls'].fname.hasError('required')">输入名字</mat-error></mat-form-field>
我也尝试为这段代码编写get函数,但结果是这样的:
获取用户(){return (this.myForm.controls.users as FormGroup).controls;}
然后尝试用 html 编写:
*ngIf=user['User'].fname.hasError('required')";
它仍然显示此错误:错误 TS7052:元素隐式具有 'any' 类型,因为类型 'AbstractControl' 没有索引签名.您的意思是调用获取"吗?
如何绑定到这些值?
你在 mat-error 上写的条件是错误的.应该是这样的:
<div formArrayName="users"><div *ngFor="让用户使用 Users.controls;让 i = 索引"[formGroupName]=i"><mat-form-field><input matInput placeholder="名字"formControlName=fname"><mat-error *ngIf="user?.get('fname')?.errors">输入名字</mat-error></mat-form-field>
I'm using Angular Material and trying to display the errors. The problem is that I can't connect to the actual value.
This is my component.ts code:
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);
}
And this is my html template:
<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>
I also tried to write get function for this code, but it turned out like this:
get User() {
return (this.myForm.controls.users as FormGroup).controls;
}
And then tried to write in html like:
*ngIf="user['User'].fname.hasError('required')"
it still shows this error: error TS7052: Element implicitly has an 'any' type because type 'AbstractControl' has no index signature. Did you mean to call 'get'?
How can I bind to those values?
You have written condition on mat-error is wrong. It should be as following:
<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>
这篇关于动态表单中的角度验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!