angular - 角度异步验证器“updateOn”和特定条件
问题描述
我试图让一个异步验证器只触发 onblur 并且如果布尔值为真。
我想我可以通过将 updateOn args 转换为数组并添加第二个对象来使其工作,如下所示:
this.createOrganisation.addControl('address', this.ofb.group(
{
addressPostcode: [null, { validators: [Validators.required], asyncValidators: [this.postCodeValidator], updateOn: [ 'blur', this.showAlert] }]
}
));
顺便提一句:
this.showAlert
设置为假。
任何人都知道如何仅验证模糊以及该布尔值是否设置为true?
解决方案
updateOn
只接受'change' | 'blur' | 'submit'
字符串并且应该只处理那些事件,你不能通过使其成为一个数组来使其工作。
据我了解,在您的案例中添加验证器的决定因素是showAlert
标志。如果 onlyshowAlert
为真,那么我们需要检查是否对blur
事件进行验证。如果这个假设是正确的并且您没有在事件showAlert
期间更新标志,blur
那么您可以使用这种方法。
我根据showAlert
标志状态设置带有和不带有验证器的表单控件。让它的 setter/getter 像:
set showAlert(val) {
this._showAlert = val
this._modifyControl()
}
get showAlert() {
return this._showAlert
}
private _modifyControl() {
if (this.showAlert) {
if (this.createOrganisation.get('addressPostcode')) {
let controlValue = this.createOrganisation.get('addressPostcode').value
this.createOrganisation.setControl('addressPostcode', new FormControl(controlValue, { validators: [Validators.required], asyncValidators: [this.postCodeValidator.bind(this)], updateOn: 'blur' }))
}
else {
this.createOrganisation.addControl('addressPostcode', new FormControl(null, { validators: [Validators.required], asyncValidators: [this.postCodeValidator.bind(this)], updateOn: 'blur' }))
}
}
else {
if (this.createOrganisation.get('addressPostcode')) {
let controlValue = this.createOrganisation.get('addressPostcode').value
this.createOrganisation.setControl('addressPostcode', new FormControl(controlValue))
} else {
this.createOrganisation.addControl('addressPostcode', new FormControl(null))
}
}
}
如果它符合您的要求,您可以使用它。
警告:
- 不要在模糊事件中更新标志。
- 如果在用户在输入框中输入时更新了标志,那么他将失去输入的焦点,因为控件将被更新。
在此处查看示例:https ://stackblitz.com/edit/updateoncontrol?file=src/app/app.component.ts
推荐阅读
- python - 如何修复 ubuntu 中的“No module named 'kivy._clock'”错误?
- python - 有没有更简单的方法来使用熊猫数据帧的每 n 行进行计算?
- python - Python - CSV文件写入同一行
- angular - 错误:“clr-icon”不是已知元素:
- sql - 链式连接导轨中的表
- matrix - 如何用逻辑构造对角矩阵?
- javascript - 从另一个 JSON 对象开始创建 JSON 对象
- kubernetes - 使用 kubectl 在 Kubernetes 上污染 InstanceGroup
- php - 如何使用 openssl 提取和验证 PDF 签名(PKCS7)?
- java - 用 nodejs 模拟一个soapUI 签名的请求