【问题标题】:Dynamic form input validation using angular 11使用 Angular 11 进行动态表单输入验证
【发布时间】:2021-04-15 02:23:55
【问题描述】:

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

如何验证每个选择字段?

【问题讨论】:

标签: angular typescript


【解决方案1】:

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

<div *ngIf="choice.errors?.required">Choice is required</div>

【讨论】:

  • 它显示控制台错误 ERROR TypeError: Cannot read property 'errors' of undefined
  • 你不能只是盲目地复制和粘贴答案中的代码。
  • 是的,我试过了,但它显示错误未定义错误
【解决方案2】:
<div *ngIf="choices.controls['choice'].errors && choices.controls['choice'].touched">
            <mat-error *ngIf="choices.controls['choice'].errors?.required">Choice {{i+1}} is required!</mat-error>
          </div>

它对我有用...

【讨论】:

  • 使用mat-error,如果你只有一个独特的错误,你不需要使用*ngIf
【解决方案3】:

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

    <mat-error>required</mat-error>

我们也使用类似的函数

  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-field 传递给函数 getErrorMessage

      <mat-form-field #inputRef appearance="fill">
        <mat-label>Enter your email</mat-label>
        <input  matInput placeholder="pat@example.com" [formControl]="email" required>
        <mat-error  >{{getErrorMessage(inputRef)}}</mat-error>
      </mat-form-field>

【讨论】:

    猜你喜欢
    • 2017-08-07
    • 2014-06-22
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    相关资源
    最近更新 更多