动态表单中的角度验证

问题描述

我正在使用 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函数,但结果是这样的:

 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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...