Angular 'keypress' 事件不提供最新的文本框值

Par*_*wal 3 keypress angular angular6

我有一个场景,我想通过进行 Http REST 调用来获取匹配的字符串,将每次击键时输入框中存在的字符串发送到服务器。但它并没有像我预期的那样工作,例如假设输入框中的当前值是“模块”,如果我在“模块”之后输入字符“e”,我希望传递给searchDepartmentsWithName 方法的值将是“模块” ' 但它给出了当前值 'modul' 而不是修改后的值 'module',后者发送到服务器并返回错误的匹配字符串。简而言之,传递给searchDepartmentsWithName方法的值始终是修改前的值。我们如何解决这个问题,或者这是否是正确的做法?

searchnox.component.html

<body>
      <input type="text" placeholder="enter department name here.." (keypress)="searchDepartmentsWithName($event.target.value)" class="ticketinginput" />
      <div *ngFor="let department of searchResults; let i = index">
      <p id="result" href="#" (click)="onClick(department)">{{ department.departmentName }}</p>
      </div>
</body>
Run Code Online (Sandbox Code Playgroud)

searchbox.component.ts

searchDepartmentsWithName(departmentName: string) {
this.serverService.searchDepartment(departmentName).subscribe( (response) => {
    console.log(response);
  },
  (error) => console.log(error)
);
this.prepareSearchResults();
}
Run Code Online (Sandbox Code Playgroud)

server.service.ts

searchDepartment(name: string) {
 this.departmentList = new Array();
const url = `http://localhost:8082/request/searchDepartmentsByName/${name}`;
return this.http.get(url).map(
  (response: Response) => {
    const data = response.json();
    for (const temp of data) {
      console.log(temp);
        const department: IDepartment = <IDepartment> temp;
        this.departmentList.push(department);
        console.log('pushing department' + department.departmentName);
    }
    this.departmentListEventEmitter.emit(this.departmentList);
    console.log(this.departmentList.length);
  }
);
}
Run Code Online (Sandbox Code Playgroud)

Saj*_*ran 10

您应该使用 keyup 而不是 keypress

(keyup)="searchDepartmentsWithName($event.target.value)"
Run Code Online (Sandbox Code Playgroud)

  • @atish keypress 通常是按下按键之后值更新之前的时刻,而 keyup 通常是两者都通过之后的时刻。 (2认同)