2017-08-11 53 views
1

我試圖做出「passwordConfirm」領域的驗證屬性「GET」,但我得到一個STANGE錯誤:ERROR TypeError: Cannot read property 'get' of undefined 這裏是我的代碼:FormGroup得到字段的值:類型錯誤:無法讀取的不確定

loginForm: FormGroup; 


ngOnInit(){ 
    this.loginForm = new FormGroup({ 
     'email': new FormControl(null, [Validators.required, Validators.email]), 
     'password': new FormControl(null, Validators.required), 
     'passwordConfirm': new FormControl(null, [Validators.required, this.checkIfMatchingPasswords.bind(this)]), 
    }); 
} 



checkIfMatchingPasswords() { 
    return this.loginForm.get('password').value === this.loginForm.get('passwordConfirm').value ? null : { notSame: true} // error 
    } 
+0

在您的自定義驗證器中嘗試'if(!this.loginForm){return null}'。 – Alex

+0

什麼都沒有發生。 – sandum

+0

很奇怪,但你可以在checkIfMatchingPasswords()作用域中嘗試this.loginForm.controls ['controlname']。value –

回答

0

通過將this綁定到驗證程序,您試圖實現的目標可能會失敗,因爲多個驗證程序函數會合併到上下文可能不同的單個函數中。

但是,如果你遵循一個validator function的足跡,你可以做到以下幾點:

checkIfMatchingPasswords(control: AbstractControl): ValidationErrors | null { 
    return control.root.get('password').value === control.value ? null : { notSame: true }; 
} 

訣竅是,每次AbstractControl知道這是parentroot

-1

解決方案是檢查loginForm是否存在。如果我做了一個console.log this.loginForm它執行三次。第一次是未定義的,並導致錯誤。我不知道它爲什麼會發生,也許這是Angular的生命週期鉤。

checkIfMatchingPasswords() { 
    if (this.loginForm) { 
     return this.loginForm.get('password').value === this.loginForm.get('passwordConfirm').value ? null : {notSame: true}; 
    } 
    } 
+0

嗯,這基本上是我說的,但不是'if(this.loginForm)'我說'if(!this.loginForm){return null} ....其餘代碼在這裏... '但是這些方法中的任何一種都適用。 – Alex

+0

你只需要記住,這個解決方案只有在'passwordConfirm'被修改時纔會被驗證:) – Alex

相關問題