Search code examples
angularkeypressangular6

Angular 'keypress' event does not give the most updated text box value


I have scenario where I want to send the string present in the input box on every keystroke to server by making Http REST call to fetch the matching strings. But it is not working as I have expected, for instance let's the say current value in the input box is 'modul', if I enter character 'e' after 'modul', i would expect the value passed to searchDepartmentsWithName method will be 'module' but instead it gives the current value 'modul' rather than the modified value 'module' which is sent to server and wrong matching strings are returned. In short the value passed to searchDepartmentsWithName method is always the value before modification. How can we solve this, or is this even the correct way of doing this?

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>

searchbox.component.ts

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

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

Solution

  • You should use keyup instead of keypress

    (keyup)="searchDepartmentsWithName($event.target.value)"