角度表单验证仅在焦点更改后起作用

use*_*835 8 forms angular-material angular angular-forms

我有一个有角度的表格,我想对其进行一些验证。现在,当第一次加载文本区域并且我输入违反验证的内容时,它不会显示错误。

当我将焦点转移到其他元素时,就会显示错误。

但是,此后每当出现违规时,都会立即显示错误,而无需更改焦点。

<form [formGroup]="AddEditform" novalidate autocomplete="off">
    <mat-form-field appearance="outline">
        <textarea matInput name="user" formControlName="users" id="user">
        </textarea>
        <mat-error
            *ngIf="!AddEditform.valid && AddEditform.get('users').hasError('maxlength')"
        >
            Exceeded maximum length
        </mat-error>
    </<mat-form-field>
</form>


AddEditform: FormGroup;

constructor(
  private fb: FormBuilder,
) { }

ngOnInit() {

  this.AddEditform = this.fb.group({
    users: [
      '',
      [
        Validators.maxLength(100)
      ],
    ],
  });
}
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种行为?为什么第一次本身,在不需要更改焦点的情况下验证不会发生?

Gau*_*rda 5

在StackBlitz Link中找到相同的解决方案

错误发生在您的 中<mat-error>,当发生输入值更改验证时不会触发。为了解决这个问题,您必须ErrorStateMatcher在 class.ts 文件中使用 custom ,并且需要在模板中告诉您需要 custom ErrorStateMatcher

组件.html

<form  novalidate autocomplete="off">
     <mat-form-field appearance="outline">
         <textarea matInput #inputValue name="user" 
              [formControl]="users" id="user" [errorStateMatcher]="matcher" >
         </textarea>
       <mat-error>
         Exceeded maximum length
       </mat-error>
    </mat-form-field>
</form> 
Run Code Online (Sandbox Code Playgroud)

组件.ts

export class AppComponent  {
    name = 'Angular';
    AddEditform: FormGroup;
    users = new FormControl('', [Validators.maxLength(5)]);
    matcher = new MyErrorStateMatcher();

    ngOnInit(){ }
}

export class MyErrorStateMatcher implements ErrorStateMatcher {
       isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
            const isSubmitted = form && form.submitted;
            return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
        }
}
Run Code Online (Sandbox Code Playgroud)


The*_*bio 2

您可以将该属性添加到表单组updateOn中:

ngOnInit() {

  this.AddEditform = this.fb.group({
    users: [
      '',
      [
        Validators.maxLength(100)
      ],
    ],
  },
 {updateOn: 'change'} 
);
}
Run Code Online (Sandbox Code Playgroud)

每次模型值发生变化时,都会触发验证。