简体   繁体   中英

Angular 2 - ES6 - trigger form validator depending on checkbox value

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM