2016-05-31 75 views
0

我試圖創建一個簡單的自定義驗證器。基本上如果一個變量(代表)是真的,該字段必須是強制性的。就這樣。Angular 2 - 自定義驗證器問題

我不知道爲什麼,但我無法代表變量。它是未定義的。有關如何處理這個問題的任何線索?

behalf = false; 
private validateName(){ 
    if (this.behalf && this.nameB.text != '') { 
     return { 
      invalidName : true 
     }; 
    } 
    else{ 
     return null; 
    } 
}  
constructor (private builder: FormBuilder){ 
    this.title = new Control('', Validators.required); 
    this.name = new Control('', this.validateName); 
    this.type = new Control('', Validators.required); 
    this.desc = new Control(''); 
    this.hideTitle = new Control(''); 
    this.end = new Control('', Validators.required); 
    this.formBook = builder.group({ 
     title: this.title, 
     name: this.name, 
     type: this.type, 
     desc: this.desc, 
     hideTitle: this.hideTitle, 
     end: this.end 
    }); 
} 

回答

3

的問題是,您引用的函數,所以當這個函數被調用的this不對應的組件對象。

你可以嘗試以下迫使功能的執行的組件實例的範圍內:

this.name = new Control('', (control) => { 
    this.validateName(control); 
}); 

或使用bind方法:

this.name = new Control('', this.validateName.bind(this)); 

使用bind時要小心方法在TypeScript中:

0

嗨,我認爲這種方法對你很有用。

addCustomerForm :any; 
constructor (private builder: FormBuilder){ 

this.customername = new Control("", Validators.compose([Validators.required, 
ValidationService.alphaValidator])); 

this.addCustomerForm = formBuilder.group({ 
    customername: this.customername, 
}); 

this.customerName = '';