0

嗨,我是采用了棱角分明(4)和我有一个自定义的验证,并通过ngIF超时设置为无角从验证消息ngIF

inValid(fieldName: string) { 
    return (
    this.form.get(fieldName).hasError('pattern') && 
    this.form.get(fieldName).dirty && 
    !this.required(fieldName) 
); 
} 

显示它,我希望延迟return响应,使得用户有时间在错误(如果有)消息显示之前键入几个字符。 name是有问题的字段的值。即的firstName

HTML

<div *ngIf="inValid(fieldName)" class="error-message"> 
    Invalid 
</div> 

理想像什么在电子邮件字段用于在https://twitter.com/signup我不想提前使用.touched

感谢。

回答

0

您也可以利用表单控件的valueChanges观察到rxjs操作debounceTime延迟响应:

  1. 进口 'rxjs /添加/运营/ debounceTime';在组件中。

2.在订阅中,您可以设置一个组件级别的变量,它包含inValid函数的结果,并且在html中需要将此变量绑定到div以切换错误消息。

this.form.get(“name”)。valueChanges.debounceTime(1000) .subscribe(data => this.error = this.inValid(data));

<div *ngIf="isError" class="error-message"> Invalid </div>

注: - 你也可以订阅表单元素水平valueChanges编写所有表单域的常见解决方案。有关详细信息,请参阅angle doc中的ValueChanged函数。

0

我建议你会使用异步验证器。这是一个例子。

异步验证需要申报任何同步验证器经过这么:

this.myForm = this.fb.group({ 
    name: ['', [], this.asyncValidator] 
}); 

这里是你的异步验证可能看起来怎么样,在这里我刚刚设置两个自定义验证,一个检查字段不为空,其他检查该字段有至少4个字符:

asyncValidator(control: FormControl): Promise<any> | Observable<any> { 
    const promise = new Promise<any>((resolve, reject) => { 
    setTimeout(() => { 
     // empty 
     if (control.value === '') { 
     resolve({'req': true}); 
     } 
     // length 
     else if(control.value.length < 4) { 
     resolve({'minl':true}) 
     } 
     else { 
     // valid 
     resolve(null); 
     } 
    }, 1000); 
    }); 
    return promise; 
} 

,然后你的模板看起来是这样的:

<div *ngIf="!myForm.get('name').pristine"> 
    <small *ngIf="myForm.hasError('req', 'name')"> Required </small> 
    <small *ngIf="myForm.hasError('minl', 'name')"> Min 4 chars </small> 
</div> 

所以现在有了这个验证器,在超时的情况下,延迟显示错误消息。