Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value in enter keypress event in angular material

Trying to create an input with a clear button following the example from Angular Material, link to the example, what I want is to get the input value on a keypress enter event.

HTML:

<mat-form-field>
  <input matInput (keydown.enter)="applyFilter($event)" placeholder="Search" 
   name="search" [(ngModel)]="searchValue">
  <button mat-icon-button matSuffix aria-label="Clear" (click)="clearSearch()">
    <mat-icon>close</mat-icon>
  </button>
</mat-form-field>

TS:

  applyFilter(event: any) {
      console.log(JSON.stringify(event)); 
  }

Results of the console when printing the event content:

{"isTrusted":true}
like image 740
ketimaBU Avatar asked Aug 13 '18 10:08

ketimaBU


People also ask

How do you check if Enter key is pressed in angular?

Check the event. And the following JavaScript code to detect whether the Enter key is pressed: const input = document. querySelector("input"); input. addEventListener("keyup", (event) => { if (event.

How does angular handle keypress events?

you can easily use keypress event in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13 and angular 14 application. When user will press key on input box field then trigger onKeypressEvent() of angular component. we will use (change) attribute for call function.

What is Keyup enter in angular?

(keyup. enter) event is used to generate event when Enter key is pressed.


1 Answers

Im not familiar with this specific scenario of the component from Material Design, But the suggestions in the comments are the traditional way to do it.
There might be an interruption from the MD component with the event, so you can try to manually pass the value to the function. something like this:

<mat-form-field>
  <input matInput #txtVal (keydown.enter)="applyFilter(txtVal.value)" placeholder="Search" 
   name="search" [(ngModel)]="searchValue">
  <button mat-icon-button matSuffix aria-label="Clear" (click)="clearSearch()">
    <mat-icon>close</mat-icon>
  </button>
</mat-form-field>

TS:

applyFilter(val: string) {
 console.log(val); 
}

#txtVal is just a local variable in the input field, so we pass its value manually to the function.

like image 169
dAxx_ Avatar answered Sep 20 '22 06:09

dAxx_