Angular 2 - ES6 - 根据复选框值触发表单验证器

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

How to trigger Form Validators in angular2

中解释了我想要实现的目标

但是其中没有解释如何将复选框状态传递到文本框的验证器。我的代码如下

组件:

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(); }
        });
    }
}

Validator函数

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

但是更新后的复选框值并未反映在调用 updateValueAndValidity() 时的验证器函数中。我在这里错过了什么?

我认为您订阅关联控件的复选框更新的方式不正确。您需要提供回调以在复选框更新时收到通知:

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

关于复选框的值,您将其作为值提供(它是原始类型而不是引用),因此 Angular2 无法更新它。要访问当前值,您需要提供控件本身(引用)并使用其值 属性:

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

下面是创建控件的新方法:

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

这里是对应的plunkr:https://plnkr.co/edit/bA3Y3G4oAk9wanzNMiS2?p=preview.