Get value in enter keypress event in angular material

ketimaBU picture ketimaBU · Aug 13, 2018 · Viewed 17.2k times · Source

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}

Answer

dAxx_ picture dAxx_ · Aug 13, 2018

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.