Get value in enter keypress event in angular material
Asked Answered
P

2

9

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}
Pergola answered 13/8, 2018 at 10:4 Comment(8)
Try with applyFilter($event.target.value) ?Exo
And since you use forms, consider using applyFilter(searchValue)Exo
@trichetriche I think not $event.target.value, it is event.target.valueIllegalize
@JavascriptLover-SKT output variables are always called $event in Angular. Same goes for (click), (input), (change) ...Exo
@trichetriche oh sorry, my mistake, I want to say that in component, we can access like event.target.valueIllegalize
@trichetriche @Javascript Lover - SKT I am getting no value, trying both $event.target.value in html or event.target.value in tsPergola
Then please provide a minimal reproducible example reproducing your issue, because on this one it works like a charm.Exo
@Pergola did you try stackblitz example provided by trichetricheIllegalize
T
12

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.

Therine answered 13/8, 2018 at 10:47 Comment(1)
works fine for me...!Tomboy
R
3

You simply need to get the value using event.target.value in your applyFilter() method.

applyFilter(event: any) {
  console.log(event.target.value); 
}

Link to StackBlitz Demo.

Ramonramona answered 13/8, 2018 at 10:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.