2016-03-07 32 views
0

我想要實現How to trigger Form Validators in angular2角2 - ES6 - 觸發形式驗證取決於複選框價值

但在解釋的,有沒有關於如何傳遞的複選框狀態進入驗證的說明文本框。我的代碼如下

組件:

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()。我在這裏錯過了什麼?

+0

什麼shouldCreateNewTeam方法的內容的內容?我認爲問題是在表單構建器中調用它時......謝謝! –

+0

已更新。在發佈這裏時重命名我的變量。不知何故錯過了這個。 –

回答

2

我認爲你沒有從相關的控制複選框更新訂閱的正確途徑。您需要提供一個回調時,該複選框被更新的通知:

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