Angular Material mat-error 组件输入时不校验解决方法

Angular About 1,241 words

场景

input第一次输入时,mat-error没有根据FormControl显示错误信息。

原因

mat-errorinput第一次输入时当input失去焦点时才显示错误信息。

解决方法

想要在input第一次输入时就可以显示校验结果,可以添加FormControl。markAsTouched()

示例代码

<div>
    <mat-form-field appearance="fill">
        <mat-label>Enter your username</mat-label>
        <input matInput placeholder="username placeholder" [(formControl)]="usernameFormControl" (change)="onUsernameChange()" >
        <mat-error *ngIf="usernameFormControl.invalid">{{getErrorMessage()}}</mat-error>
    </mat-form-field>
</div>
import {Component, OnInit} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';

@Component({
  selector: 'app-username',
  templateUrl: './username.component.html',
  styleUrls: ['./username.component.scss'],
})
export class UsernameComponent implements OnInit {
  public usernameFormControl: FormControl;
  constructor() {}

  ngOnInit(): void {
    this.usernameFormControl = new FormControl('', Validators.maxLength(16)); 
    this.usernameFormControl.markAsTouched();
  }

  onUsernameChange() {
    console.log('onUsernameChange')
  }

  getErrorMessage() {
    return this.usernameFormControl.hasError('maxlength') ? 'username length is 16' : '';
  }
}
Views: 2,897 · Posted: 2021-06-21

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh