【问题标题】:Angular 2 - ES6 - trigger form validator depending on checkbox valueAngular 2 - ES6 - 根据复选框值触发表单验证器
【发布时间】:2016-06-20 17:14:39
【问题描述】:

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

验证器功能

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

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

【问题讨论】:

  • shouldCreateNewTeam方法的内容是什么?我认为问题在于在表单构建器中调用它时......谢谢!
  • 已更新。在此处发布时重命名了我的变量。不知何故错过了这个。

标签: javascript angular ecmascript-6 angular2-forms


【解决方案1】:

我认为您没有以正确的方式从关联控件中订阅复选框更新。您需要提供一个回调,以便在复选框更新时收到通知:

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。

【讨论】:

    猜你喜欢
    • 2017-06-21
    • 2019-08-18
    • 2017-03-06
    • 1970-01-01
    • 2015-03-21
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多