使用angular 11进行动态表单输入验证

使用angular 11进行动态表单输入验证,angular,typescript,Angular,Typescript,我在angular11中创建了动态表单输入。需要通过单击“添加”按钮来验证动态添加的表单字段。我找不到正确的解决办法。这是我的密码 在component.ts文件中 this.pollAdd = this.fb.group({ question: ['',Validators.required], queChoices:this.fb.array([this.createChoice()]), }); addChoice(){ this.queChoic

我在angular11中创建了动态表单输入。需要通过单击“添加”按钮来验证动态添加的表单字段。我找不到正确的解决办法。这是我的密码

在component.ts文件中

this.pollAdd = this.fb.group({
      question: ['',Validators.required],
      queChoices:this.fb.array([this.createChoice()]),
    });

addChoice(){
    this.queChoices=this.pollAdd.get('queChoices') as FormArray;
    this.queChoices.push(this.createChoice());
  }

  createChoice():FormGroup{
    return this.fb.group({
      choice:['',Validators.required],
    })
  }

get f() { return this.pollAdd.controls; }
在component.html文件中

<div formArrayName="queChoices" *ngFor="let choices of pollAdd.get('queChoices')['controls'];let i=index;">
        <mat-form-field class="ch__custom_input w-100 mt-3" [formGroupName]="i">
          <mat-label>Choice {{i+1}}</mat-label>
          <input matInput formControlName="choice" autofocus/>
        </mat-form-field>
      </div>

选择{{i+1}

如何验证每个选项字段?

获取名称并检查是否有错误,就像常规表单一样

<div *ngIf="choice.errors?.required">Choice is required</div>
需要选择

必须选择{i+1}}!

它对我有用…

使用mat error,如果我们只有一个唯一的错误,我们不需要使用*ngIf,所以它很简单

必需
我们还使用一个函数,如

  getErrorMessage(inputRef:MatFormField) {
    const control=inputRef._control?inputRef._control.ngControl:null;
    if (!control || !control.errors)
      return null;
    if (control.hasError('required')) {
      return 'You must enter a value';
    }

    return control.hasError('email') ? 'Not a valid email' : '';
  }
并使用模板引用变量将mat字段传递给函数getErrorMessage


输入您的电子邮件
{{getErrorMessage(inputRef)}

its显示控制台错误类型错误:无法读取未定义的属性“errors”您不能从答案中盲目复制和粘贴代码。是的,我尝试过,但其显示错误未定义错误这是否回答了您的问题?使用
mat error
,如果只有唯一的错误,则无需使用*ngIf
  getErrorMessage(inputRef:MatFormField) {
    const control=inputRef._control?inputRef._control.ngControl:null;
    if (!control || !control.errors)
      return null;
    if (control.hasError('required')) {
      return 'You must enter a value';
    }

    return control.hasError('email') ? 'Not a valid email' : '';
  }