Angular 4 自定义验证器 ngIf 不显示错误 <span>
Angular 4 Custom Validator ngIf not displaying error <span>
我创建了 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)
});
}
你有错别字...
*ngIf="username.errors.cannotHaveSpace"
*ngIf="username.errors.shouldBeUnique"
应该...
*ngIf="username.errors.cantHaveSpace"
*ngIf="username.errors.shouldbeUniqe"
不显示您的 TS 代码,但还要确保异步验证器被标记为它自己的数组中的第三个参数:)
我创建了 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)
});
}
你有错别字...
*ngIf="username.errors.cannotHaveSpace"
*ngIf="username.errors.shouldBeUnique"
应该...
*ngIf="username.errors.cantHaveSpace"
*ngIf="username.errors.shouldbeUniqe"
不显示您的 TS 代码,但还要确保异步验证器被标记为它自己的数组中的第三个参数:)