Angular 角度5:TypeError:无法读取属性';密码';未定义的

Angular 角度5:TypeError:无法读取属性';密码';未定义的,angular,typescript,Angular,Typescript,我试图编写一个自定义密码匹配验证器,当我键入两个不同的密码时,控制台中出现一个TypeError。我使用角材质控件和类进行验证。如果可能的话,我想避免使用反应表单和表单组。我一直在尝试几种方法,但无法让确认密码方法工作。任何帮助都将不胜感激!谢谢 打字稿: import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from "@angular/forms"; i

我试图编写一个自定义密码匹配验证器,当我键入两个不同的密码时,控制台中出现一个TypeError。我使用角材质控件和类进行验证。如果可能的话,我想避免使用反应表单和表单组。我一直在尝试几种方法,但无法让确认密码方法工作。任何帮助都将不胜感激!谢谢

打字稿:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from "@angular/forms";
import { Router } from '@angular/router';

@Component({
    templateUrl: './password-reset.component.html',
    styleUrls: ['./password-reset.component.css']
})
export class PasswordResetComponent {
    hide = true;
    imageSrc = '../../assets/images/logo.png';
    password = new FormControl('', [Validators.required, 
     Validators.minLength(8)]);
    confirm_password = new FormControl('', [Validators.required, 
    Validators.minLength(8)], this.passwordMatchValidator);


    passwordMatchValidator(FormControl) {
       return this.password.value !== this.confirm_password.value
       ? null : { 'mismatch': true };
    }
     getPasswordErrorMessage() {
       return this.password.hasError('required') ? 'Please enter a password' 
         :
        this.password.hasError('minlength') ? 'Password must be at least 8 
         characters' :

        '';
     }
   getConfirmPasswordErrorMessage() {
      return this.confirm_password.hasError('required') ? 'Please enter a 
      password' :
      this.confirm_password.hasError('minlength') ? 'Password must be at 
       least 8 characters' :
       this.confirm_password.hasError(this.passwordMatchValidator) ? 
      'Passwords must match' :

        '';
     }


  }
HTML:


{{getPasswordErrorMessage()}}
{{隐藏?'visibility_off':'visibility'}
{{getConfirmPasswordErrorMessage()}}
{{隐藏?'visibility_off':'visibility'}

此处的错误表示未定义的“this”。 尝试创建函数的绑定版本

this.passwordMatchValidator.bind(this)
这里的问题是,函数不是立即调用的,而是在angular调用验证器时作为回调调用的,因此“this”上下文丢失。bind确保了这一点。有关更多信息,请在TypeScript中输入“this”-可能重复的
this.passwordMatchValidator.bind(this)