Search code examples
angularangular-forms

Cannot read property 'get' of undefined while writing validator in angular 6


I am trying write a validator to match password in angular 6, below is the code of component class

export class comnentClass implements OnInit {


  addAccountForm = new FormGroup({
      "username": new FormControl('',
    [ Validators.required],this.shouldContainUniqueUsername.bind(this)), 
    "password": new FormControl('', Validators.required),
    "confirmPassword": new FormControl('',[Validators.required,this.checkPasswords.bind(this)]),
  });

  get username() {
    return this.addAccountForm.get('username');
  }

  get password() {
    return this.addAccountForm.get('password');
  }

  get confirmPassword() {
    return this.addAccountForm.get('confirmPassword');
  }

  onSubmit() {
  }

checkPasswords(control: AbstractControl) { 

let pass = this.password;
  console.log("password is "+pass)
  return pass === control.value ? null : { notSame: true }     
}

}

Every time when angular load component class, I am getting below exception

core.js:1598 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'get' of undefined
TypeError: Cannot read property 'get' of undefined
    at SysAdminComponent.get [as password] (sys-admin.component.ts:53)

How can I get the values of other input type while writing validator to match password?


Solution

  • Replace this below code of password property get method.

      get password() {
        return this.addAccountForm ? this.addAccountForm.get('password') : null;
      }

    The problem is you are binding checkPasswords validator in confirmPassword property and inside this metho you are calling password property formcontrol. because 'addAccountForm' is not defined.

    please check working sample on stackblitz

    I would suggest if you want to compare the password, then please refer this answer Confirm password validation in angular 6 .

    Any confusion please let me know.