初始化时要验证的角形字段

时间:2019-02-05 19:20:55

标签: angular

我建立了一个模板驱动的表单,其中包含一个字段表。表的一行中的一个数据项具有这样的“路径名”字段。 (这在* ngFor结构内部)

      <td>
        <mat-form-field>
          <input #fieldPath="ngModel" type="text" matInput [(ngModel)]="f.pathName"
                 name="pathname{{ row }}"
                 required appPathnameValidator appPathInUseValidator [parentId]="parent.id"
                 placeholder="Path name">
          <mat-error *ngIf="fieldPath.errors?.pattern">Path Name cannot include white space or / character.</mat-error>
          <mat-error *ngIf="fieldPath.errors?.required">Path Name is Required.</mat-error>
          <mat-error *ngIf="fieldPath.errors?.pathInUse">Path Name Is In Use</mat-error>
        </mat-form-field>
      </td>

因此,我有一个内置的和两个自定义验证器。当用户访问表单控件并离开它时,所有这些都起作用。但是,表单的初始化方式可能具有未通过验证的起始值。但是 mat-error 元素当时未显示。

有什么方法可以强制验证这些字段而无需用户访问?

2 个答案:

答案 0 :(得分:1)

我不使用mat-error,并且完全控制消息出现的时间:立即(这是标准的角度默认值),仅当触摸了该字段,修改了该字段时(脏) )或任何组合。

  <div class="form-group row mb-2">
    <label class="col-md-2 col-form-label"
           for="firstNameId">First Name</label>
    <div class="col-md-8">
      <input class="form-control"
             id="firstNameId"
             type="text"
             placeholder="First Name (required)"
             required
             minlength="3"
             [(ngModel)]=customer.firstName
             name="firstName"
             #firstNameVar="ngModel"
             [ngClass]="{'is-invalid': (firstNameVar.touched || firstNameVar.dirty) && !firstNameVar.valid }" />
      <span class="invalid-feedback">
        <span *ngIf="firstNameVar.errors?.required">
          Please enter your first name.
        </span>
        <span *ngIf="firstNameVar.errors?.minlength">
          The first name must be longer than 3 characters.
        </span>
      </span>
    </div>
  </div>

在此代码中,如果消息是toucheddirty而不是valid,则显示消息。我假设您只希望valid不想要立即显示消息。

答案 1 :(得分:0)

DeborahK为我提供了我所需的提示,但我将在此处记录我的解决方案,以使可能需要它的人受益。

我可以通过 @ViewChild 参考访问表单。在模板中:

  <form #tform="ngForm" >

并在组件中:

  @ViewChild('tform') form: NgForm;

现在,在构建表单之后,我可以像这样遍历所有 FormControl

    for (const key of Object.keys(this.form.controls)) {
      const control = this.form.controls[key];
      if (!control.valid) control.markAsTouched();
    }

请注意,这些字段已经过验证,因此将设置 valid 属性。但是, markAsTouched 方法的效果允许根据结果显示 mat-error 元素。

相关问题