2

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?

Community
  • 1
  • 1
Varun Mulloli
  • 658
  • 13
  • 28

1 Answers1

4

I think that you don't subscribe the right way for checkbox updates from the associated control. You need to provide a callback to be notified when the checkbox is updated:

this.checkbox.valueChanges
    .subscribe(
      (value) => { this.name.updateValueAndValidity(); }
    );

Regarding the value of the checkbox, you provide it as value (it's a primitive type not a reference) so Angular2 can't update it. To have access to the current value, you need to provide the control itself (reference) and use its value property:

function nameValidator(checkboxCtrl) {
  return function(control) {
    let checkbox = checkboxCtrl.value;
      if (checkbox && !control.value)
          return { required: true };
      return null;
  }
}

Here is the new way to create the controls:

this.checkbox = new Control(false);
this.name = new Control('', nameValidator(this.checkbox));

Here is the corresponding plunkr: https://plnkr.co/edit/bA3Y3G4oAk9wanzNMiS2?p=preview.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360