首先,我有这个异步验证器用于密码验证的角度,我试图在html中延迟消息,但它似乎没有工作,我怎么需要调用它工作 . 我通过console.log检查(控制)在函数中它返回预期的结果,但它仍然立即出现在我如何在HTML代码中调用它 .
我将把示例代码放在这里 . 在这里,我使用验证器制作表格 .
constructor(fb: FormBuilder)
{
this.form = fb.group({
password: ['', Validators.required,this.asyncValidator],
confirmPassword: ['', Validators.required,this.asyncValidator]
})
}
这是验证功能 .
asyncValidator(control:FormControl):any{
return new Promise(
(resolve) =>{
setTimeout(() => {
if((control.password).length < 6 && (control.password).length > 1)
console.log("true");
console.log("false");
resolve(null);
},2000);
}
);
}
这是我在页面中使用的HTML代码,用于查看延迟的消息(不起作用) .
<div class="alert alert-danger"
*ngIf="asyncValidator(this.form.controls.password)">Password too short</div>
我如何使用异步验证器,以便我的HTML中的消息出现延迟2秒?
1 回答
您似乎误解了异步验证器的作用以及它们的使用和编写方式 . 因此,您的实施存在很多问题 . 这是你如何解决它们 .
1. Get rid of the code in your constructor and move it to ngOnInit:
Rationale:
constructor
s应该是瘦的according to Misko Hevery并且,async验证器作为第三个参数传递给FormControl
此外,由于
async
验证器是将由Angular而不是我们调用的函数,我们需要通过在异步验证器函数上调用bind(this)
来显式设置this
的上下文 .2. Now, the promise returned by the asyncValidator, should resolve to null in case of no error and an error object in case of an error:
3. Create a function that is going to return a boolean based on whether a FormControl is touched and has an error that you're returning from your asyncValidator function:
Rationale: 这是我们将在模板中使用的内容 .
4. Update your template to show the error only if the input field is touched and has that error:
这是你的参考Working Sample Stackblitz .