简体   繁体   English

在 Angular 中一段时间后如何在 mat-input 上设置错误?

[英]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 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 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.我需要在 1 秒键入结束后显示验证消息。 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 .每个控件都公开了一个可观察的valueChanges ,您可以利用它并使用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 .这里找到工作演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Mat收音机内为Mat输入设置焦点 - How can I set focus for mat-input inside the mat-radio 角度禁用按钮和mat输入错误消息 - Angular disabling button and mat-input error message 如何在 ngx-mat-intl-tel-input 上设置初始值(NgxMatIntlTelInput - Angular 材料的国际电话输入) - How to set Initial value on ngx-mat-intl-tel-input (NgxMatIntlTelInput - International Telephone Input for Angular Material) 如何在 mat-datepicker 输入中设置显示一些字符串,但在后端它只是发送的日期 - How to set show some string in mat-datepicker input but in backend it is only the date that is sending 如何在 Angular 中关闭 mat-select-filter 下拉菜单后重置搜索输入值? - How to reset search input value after close mat-select-filter drop-down in Angular? 为角材料设置输入 mat-form-fields 的宽度 - Set width on input mat-form-fields for angular material 如何将动画图标设置为在一段时间后停止 - How to set animated icons to stop after some time 在正确的时间更改Angular后,如何选择输入中的文本? - How to select text in an input after a change in Angular at the right time? 如何在设定的时间间隔后以角度附加文字? - how to append text in angular after set interval of time? Angular @Input 消息仅设置为第一次 - Angular @Input message is set only for the first time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM