Angular Form 控件在组件初始化时无效,无需执行任何操作

Aza*_*lov 2 angular angular-reactive-forms

在组件初始化时,所有带有验证器的表单控件都被标记为无效,而不采取任何操作。

component.html

<form [formGroup]="form" (ngSubmit)="submit()">
  <input type="text" formControlName="phone" [class.error]="form.get('phone').invalid">
  <button type="submit">goo</button>
</form>
Run Code Online (Sandbox Code Playgroud)

component.ts

import { Component, VERSION } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  form: FormGroup;

  constructor(public fb: FormBuilder) {
      this.form = this.fb.group({
          phone: [
              null,
              [Validators.required, Validators.minLength(9), Validators.maxLength(9), Validators.pattern('^[0-9]*$')]
          ]
      });

      console.log(this.form);
  }

  submit() {
      if (this.form.invalid) return;

      console.log(this.form.value);
  }
}

Run Code Online (Sandbox Code Playgroud)

斯塔克闪电战

pei*_*ent 5

您还需要查看表单和表单控件上的其他属性。鉴于您的问题,我相信以下内容应该可以解决您的问题:

    <form [formGroup]="form" >
      <input type="text" formControlName="phone" [class.error]="form.get('phone').invalid && form.get('phone').touched">
      <button type="submit">goo</button>
    </form>
Run Code Online (Sandbox Code Playgroud)

该解决方案会增加form.get('phone').touched您的class.error支票。由于空白页电话输入无法通过验证器,因此即使尚未触及,它也会被标记为“错误”。您还可以添加对 Touched 的检查,这将导致表单在加载时不显示“错误”类,但仅在用户访问该输入并且其中的值无效之后才显示。