Home > front end >  How do I add a listener to a search form in Angular material?
How do I add a listener to a search form in Angular material?

Time:02-10

I'm working with Angular material and I have a search form. As shown in the following code, I have a button and after a click event on the button, the words written in the search form are given to the searchProductByName method as parameters. I'd like to substitute the button with a listener that, after having written something in the form and having clicked on enter (instead of the button), grabs the things written in the search form and passes them to the searchProductByName method as parameters. Is there a way to do so?

<form  >
    <mat-form-field  appearance="fill">
      <mat-label >Search</mat-label>
      <input #input type="text" ngModel name="name"  id="name"
             aria-label="Search"
             matInput
             >
             <button (click)="searchProductByName(input.value)" routerLink="/products/searchProduct/by_name"  routerLinkActive="active">Go</button>

    </mat-form-field>
  </form>

CodePudding user response:

Easy way to do that in template is add keyup event to the input:

<form  >
    <input #input type="text" ngModel name="name"  id="name"
         (keyup.enter)="searchProductByName(input.value)" 
         aria-label="Search"
         matInput
         >
    <button (click)="searchProductByName(input.value)" routerLink="/products/searchProduct/by_name"  routerLinkActive="active">Go</button>

  </mat-form-field>
</form>

Or you can get your input element in component with ViewChild and make listener there.

CodePudding user response:

If the searchPruductByName is a method that is using http request to search from backend, for example - I would suggest to also implement debounce'ing the search as well. Otherwise it would search with each keystroke. A nice elegant way would be to use a debounce decorator. https://medium.com/time-machine/how-to-implement-debounce-decorator-2e963b70cd27

<form  >
    <input #input type="text" ngModel name="name"  id="name"
         (input)="searchProductByName($event)" 
         aria-label="Search"
         matInput>
  </mat-form-field>
</form>

To navigate to link on pressing "Enter" add to constructor Router and then use router to navigate.

constructor(router: Router) {}

onNavigate() {
// other stuff
this.router.navigateByUrl('/products/searchProduct/by_name')
}
<input (keyup.enter)="searchProductByName(input.value); onNavigate()">
  • Related