首页 > 解决方案 > 如何解决错误类型错误:这是未定义的 [Angular]

问题描述

我正在使用 Angular 9 来解决这个问题。已经有一个问题(7 年前问过):

类型错误:这是未定义的

但这不是很有帮助。我检查了其他类似的问题:

Angular2组件的“this”在执行回调函数时未定义

我想在输入字段上的每次击键时调用一个方法。

HTML

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

打字稿

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
  }
}

但是我每次击键都会得到这个:

在此处输入图像描述

请纠正我的错误。

标签: javascriptangular

解决方案


工作解决方案:

HTML:

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

组件.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");
      }
    }
    
  }

推荐阅读