【发布时间】:2016-06-20 17:14:39
【问题描述】:
How to trigger Form Validators in 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() 时的验证器函数中。我在这里错过了什么?
【问题讨论】:
-
shouldCreateNewTeam方法的内容是什么?我认为问题在于在表单构建器中调用它时......谢谢!
-
已更新。在此处发布时重命名了我的变量。不知何故错过了这个。
标签: javascript angular ecmascript-6 angular2-forms