What i'm trying to achieve is explained in How to trigger Form Validators in angular2
But in that, there's no explanation about how do you pass the checkbox state into the validator for the text box. My code is as follows
The Component:
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(); }
});
}
}
The Validator function
function nameValidator(checkbox) {
return function(control) {
if (checkbox && !control.value)
return { required: true };
return null;
}
}
But the updated checkbox value is not reflected in the validator function on calling updateValueAndValidity()
. What am I missing here?