简体   繁体   中英

How to set an errors on mat-input after some time in Angular?

I need to show validation error on input field after some time delay. So far I have this code.

html

<form  [formGroup]="myGroup">
  <mat-form-field>
    <mat-label>Age</mat-label>
    <input matInput formControlName="age" placeholder="0">
  </mat-form-field>

  <span class="error" *ngIf="myGroup.get('age').hasError('maxlength')">age should be max 2 digits.</span>
</form>

typescript

myGroup: FormGroup;

constructor () {
this.myGroup = new FormGroup({
    age: new FormControl(null, {
    validators: [Validators.maxLength(2)]
    }),
 });
}

I need to show the validation message after 1 seconds typing ends. how to do it.

In your case you don't have to use the control validator mechanism. you can create an alternative which fully control your selves. Every control exposes a valueChanges observable that you can take advantage of, and use RxJS debounceTime .

  myGroup: FormGroup;

  constructor () {
    this.myGroup = new FormGroup({
      age: new FormControl(null)
    });
  }

  ngOnInit() {
    const age = this.myGroup.get('age');
    if (age) {
      age.valueChanges.pipe(
            debounceTime(1000)
        ).subscribe(() => age.setErrors(Validators.maxLength(2)(age)))
    }
  }

I found above code from this great medium article .

Find working demo Here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM