角度 2 - ES6 - 根据复选框值触发表单验证器
Angular 2 - ES6 - trigger form validator depending on checkbox value
我想要实现的目标在如何在 angular2 中触发表单验证器中进行了解释
但是,没有关于如何将复选框状态传递到文本框的验证器中的解释。我的代码如下
组件:
export class FormComponent {
static get annotations() {
return [
new Component ({
templateUrl: "./form.component.html",
directives: [FORM_DIRECTIVES],
})
];
}
static get parameters() {
return [[FormBuilder]];
}
constructor (formbuilder) {
this.checkbox = new Control(false);
this.name = new Control('', nameValidator(this.checkbox.value));
this.myForm = formbuilder.group({
checkbox: this.checkbox,
name: this.name,
});
this.checkbox.valueChanges
.subscribe({
next: (value) => { this.name.updateValueAndValidity(); }
});
}
}
验证器函数
function nameValidator(checkbox) {
return function(control) {
if (checkbox && !control.value)
return { required: true };
return null;
}
}
但是更新的复选框值不会反映在调用updateValueAndValidity()
的验证器函数中。我在这里错过了什么?
我认为您没有以正确的方式订阅来自关联控件的复选框更新。您需要提供一个回调,以便在复选框更新时收到通知:
this.checkbox.valueChanges
.subscribe(
(value) => { this.name.updateValueAndValidity(); }
);
关于复选框的值,您可以将其作为值提供(它是基元类型而不是引用),因此 Angular2 无法更新它。若要访问当前值,需要提供控件本身(引用)并使用其 value 属性:
function nameValidator(checkboxCtrl) {
return function(control) {
let checkbox = checkboxCtrl.value;
if (checkbox && !control.value)
return { required: true };
return null;
}
}
以下是创建控件的新方法:
this.checkbox = new Control(false);
this.name = new Control('', nameValidator(this.checkbox));
这是相应的 plunkr:https://plnkr.co/edit/bA3Y3G4oAk9wanzNMiS2?p=preview。
相关文章:
- 解析javascript表单验证器
- Jquery表单验证插件-如果选中复选框,如何在提交时执行某些操作
- 自定义表单验证和提交
- Javascript表单验证的缺点
- Jquery的表单验证不起作用
- 语义ui表单验证:图像url
- jQuery表单验证适用于Mozilla和Internet Explorer,但不适用于Chrome或Safari
- JavaScript表单验证-“;“错误”;不按需要工作
- Mailchimp内联表单验证不适用于JS加载的HTML
- jQuery/JS获胜't在表单验证后重定向
- jquery表单验证复选框错误显示
- javascript表单验证-数值和密码
- 我想知道如何在javascript中进行表单验证
- jQuery表单验证(如果==“执行此操作”)仅适用于第一次输入
- 使用记录保存的消息进行表单验证
- 表单验证工作不正常,在不检查条目的情况下继续
- 如何对未知表单元素进行表单验证
- 使用ajax、php和mysql进行表单验证
- JS表单验证未发生
- 表单验证jsphp路径