[英]How to set an errors on mat-input after some time in Angular?
延迟一段时间后,我需要在输入字段上显示验证错误。 到目前为止,我有这个代码。
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)]
}),
});
}
我需要在 1 秒键入结束后显示验证消息。 怎么做。
在您的情况下,您不必使用控制验证器机制。 您可以创建一个完全控制自己的替代方案。 每个控件都公开了一个可观察的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)))
}
}
我从这篇很棒的媒体文章中找到了上面的代码。
在这里找到工作演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.