[英]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 .我从这篇很棒的媒体文章中找到了上面的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.