我创建了2个自定义表单验证器,它们都正常工作,但是当我在模板中使用ngIf条件时,不会显示该消息。但是,对于构建验证器,将显示消息。这两个验证器都在组件中注册,控制台中没有错误。
组件模板:
<label for="username">Username</label>
<input formControlName='username' type="text" id="username" class="form-control">
<div *ngIf="username.touched && username.invalid">
<span class="text-danger" *ngIf='username.errors.required'>Username is required</span>
<span class="text-danger" *ngIf="username.errors.minlength">Username should be min {{ username.errors.minlength.requiredLength }} characters</span>
<span class="text-danger" *ngIf='username.errors.cannotHaveSpace'>Username can't have space (Custom Validation)</span>
<span class="text-danger" *ngIf="username.errors.shouldBeUnique">Username is already taken (Custom Validation)</span>
</div>
验证者代码:
static cannotHaveSpace(control: AbstractControl) : ValidationErrors | null{
if((control.value as string).indexOf(' ')>=0)
return {cantHaveSpace: true};
return null;
}
static shouldBeUnique(control: AbstractControl): Promise< ValidationErrors | null >{
return new Promise((resolve,reject)=>{
setTimeout(()=>{
if(control.value=='Saad')
resolve({shouldbeUniqe:true});
else resolve(null);
},2000)
});
}
答案 0 :(得分:0)
你有错别字......
*ngIf="username.errors.cannotHaveSpace"
*ngIf="username.errors.shouldBeUnique"
应该是......
*ngIf="username.errors.cantHaveSpace"
*ngIf="username.errors.shouldbeUniqe"
不显示您的TS代码,但也要确保异步验证器被标记为其自己的数组中的第三个参数:)