2017-08-11 5 views
1

の「取得」プロパティを読み取ることができません:ここERROR TypeError: Cannot read property 'get' of undefined は私のコードです:フィールドの値を取得FormGroup:私は「passwordConfirm」フィールドの検証を作るしようとしているが、私はスタンジェのエラーを取得し、未定義

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 
    } 
例外TypeErrorが
+0

カスタムバリデーターで 'if(!this.loginForm){return null}'を試してください。 – Alex

+0

何も起こりません。 – sandum

+0

非常に奇妙ですが、this.loginForm.controls ['controlname']。値 –

答えて

0

thisをバリデーターにバインドすることによって達成しようとしているのは、複数のバリデーター関数がコンテキストが異なる可能性のある単一の関数にマージされるため、おそらく失敗するでしょう。あなたがvalidator functionの足跡をたどる場合は、次の操作を行うことができ

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

トリックは、各AbstractControlは、それがparentrootだ知っているということです。

-1

解決策は、loginFormが存在するかどうかを確認することです。私がthis.loginFormのconsole.logを実行すると、3回実行されます。最初の時刻は未定義で、エラーの原因となっていました。私はなぜそれが起こるか、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

関連する問題