【问题标题】:Angular validation within dynamic forms动态表单中的角度验证
【发布时间】:2021-09-26 17:08:14
【问题描述】:

我正在使用 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: ['', 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:元素隐式具有“任何”类型,因为类型“AbstractControl”没有索引签名。您的意思是调用“get”吗?

如何绑定到这些值?

【问题讨论】:

  • 我的回答对你有帮助吗?

标签: angular validation angular-material nested nested-forms


【解决方案1】:

你在 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>

【讨论】:

  • 如果你正在使用material和mat-error并且你有一个独特的错误你不需要使用*ngIf,material error还没有考虑到这一点
猜你喜欢
  • 2014-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多