Issue
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 class="search-form" >
<mat-form-field class="example-full-width" appearance="fill">
<mat-label >Search</mat-label>
<input #input type="text" ngModel name="name" class="form-control" id="name"
aria-label="Search"
matInput
>
<button (click)="searchProductByName(input.value)" routerLink="/products/searchProduct/by_name" routerLinkActive="active">Go</button>
</mat-form-field>
</form>
Solution
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 class="search-form" >
<input #input type="text" ngModel name="name" class="form-control" id="name"
(input)="searchProductByName($event); onInput($event)"
aria-label="Search"
matInput>
</mat-form-field>
</form>
onInput(event: any) {
console.log(event.target.value);
}
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()">
Answered By - Joosep.P
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.