Angular 2 - ES6 - trigger form validator depending on checkbox value
我要达到的目的在如何触发angular2中的表单验证器中进行了解释
但是,关于如何将复选框状态传递到文本框的验证器中,没有任何解释。我的代码如下
组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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(); } }); } } |
验证器功能
1 2 3 4 5 6 7 | function nameValidator(checkbox) { return function(control) { if (checkbox && !control.value) return { required: true }; return null; } } |
但是在调用
我认为您没有从关联的控件中订阅复选框更新的正确方法。您需要提供一个回调,以便在更新复选框时得到通知:
1 2 3 4 | this.checkbox.valueChanges .subscribe( (value) => { this.name.updateValueAndValidity(); } ); |
关于复选框的值,您将其提供为值(它是原始类型而不是引用),因此Angular2无法更新它。要访问当前值,您需要提供控件本身(引用)并使用其value属性:
1 2 3 4 5 6 7 8 | function nameValidator(checkboxCtrl) { return function(control) { let checkbox = checkboxCtrl.value; if (checkbox && !control.value) return { required: true }; return null; } } |
这是创建控件的新方法:
1 2 | this.checkbox = new Control(false); this.name = new Control('', nameValidator(this.checkbox)); |
这是相应的插件:https://plnkr.co/edit/bA3Y3G4oAk9wanzNMiS2?p=preview。