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?

2
  • What is the content of the content of the shouldCreateNewTeam method? I think the problem is when calling it in the form builder... Thanks! Commented Mar 7, 2016 at 8:13
  • Updated. Renamed my variables while posting here. Missed this somehow. Commented Mar 7, 2016 at 8:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.