2016-05-31 4 views
0

私は単純なカスタムバリデータを作成しようとしています。基本的に1つの変数(真偽)が真の場合、フィールドは必須でなければなりません。それで全部です。角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方法使用:bindを使用した場合

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

は注意が必要ですがタイプスクリプトのメソッド:

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 = ''; 
関連する問題