2016-07-25 53 views
0

我與Angular2表單驗證和棒試驗,以檢查是否值已經採取:給予額外的參數,以自定義驗證

namesArray = Users[]; 
ngOnInit() { 
this.myForm = this.fb.group({ 
     name: ['', Validators.compose([ 
     Validators.required, 
     this.nameValidator 
     ]) 
     ], 
}) 
} 

nameValidator(control:FormControl):{[key:string]:boolean} { 
    console.log(this.namesArray); 
    return null; 
} 

這將返回我一個錯誤:

無法讀取屬性「 namesArray'的undefined

當我打印this是返回undefined。那麼如何訪問函數外部的數組?

+0

你極力挽留像'this.nameValidator.bind(這)'背景? – yurzui

回答

4

你需要脂肪箭頭功能通過保留this

ngOnInit() { 
this.myForm = this.fb.group({ 
     name: ['', Validators.compose([ 
     Validators.required, 
     (control) => this.nameValidator(control as FormControl) 
     ]) 
     ], 
}) 
} 

更多脂肪箭頭位置:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

+0

返回''AbstractControl'類型的參數不能分配給'FormControl'類型的參數 – mimo

+0

嘿,我編輯它。您可以在使用胖箭頭時將其轉換爲「FormControl」,或更改驗證函數的簽名以允許「AbstractControl」參數。 –