Tanzeel
Tanzeel

Reputation: 4998

How to solve ERROR TypeError: this is undefined [Angular]

I'm facing this with Angular 9. There is already a question (asked 7 years ago):

TypeError: this is undefined

But it wasn't very helpful. I checked other questions also like this:

Angular2 component's “this” is undefined when executing callback function

I want to call a method with every keystroke on an input field.

HTML

<input ... type="text" (input)="crossCheckUsername()" placeholder="Enter username">

Typescript

constructor(..., private _userService: UserService) { 
   // nothing here 
}

ngOnInit() {
  // nothing here
}

// users is defined properly; it is hard coded in the starting only

isUserExists(): boolean {
  let userExists = false;
  this.users.forEach(function (user) {
    if(*some logic*) {
        userExists=true;
    }
    else {
      userExists=false;
    }
  })
  return userExists;
}

crossCheckUsername() {  // this method will be called on every key stroke
  if(this.isUserExists()) {
    console.log("Try a different username");
  }
  else {
    //do nothing; keep typing
  }
}

But I'm getting this with every keystroke:

enter image description here

Please correct my mistake.

Upvotes: 1

Views: 6404

Answers (1)

Mohit Kumar
Mohit Kumar

Reputation: 160

Working solution:

HTML:

<input formControlName="username" type="email" class="form-control" id="usernameInput" (input)="crossCheckUsername($event.target.value)" placeholder="Enter username">

Component.ts:

crossCheckUsername(username: any) {

    for (let i = 0; i < this.users.length; i++) {
      if (this.users[i].email == username) {
        console.log("already exists");
      }
      else {
        console.log("ok keep typing");
      }
    }
    
  }

Upvotes: 1

Related Questions