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

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

本文关键字:表单 验证 复选框 ES6 角度      更新时间:2023-09-26

我想要实现的目标在如何在 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(); }
        });
    }
}

验证器函数

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 无法更新它。若要访问当前值,需要提供控件本身(引用)并使用其 value 属性:

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。