'How to create search data in angular?
I tried to create search input but something went wrong! Here is html
<div>
<input type="search" id="searchTerm" name = "searchTerm" placeholder="Search Food Mine!" (ngSubmit)="search()">
<button (click)="search()">Search</button>
</div>
Here is Angular component
searchTerm:string;
constructor(private router: Router) { }
search():void{
this.router.navigateByUrl('/search/'+ this.searchTerm);
}
it's seem like fail in data between html and Angular component. Im trying to get data of input text to search() in component. But seem like it failed.
Solution 1:[1]
Just change your template to:
<div>
<input type="search" id="searchTerm" [(ngModel)]="searchTerm" placeholder="Search Food Mine!">
<button (click)="search()">Search</button>
</div>
Don't forget to import FormsModule in your module (AppModule probably) like this:
import { FormsModule } from '@angular/forms';
...
@NgModule({
imports: [
...,
FormsModule
]
}
...
Solution 2:[2]
i tried this way and it work!
HTML
<input type="search" name="search-box" class="form-control" placeholder="Search" class=" w-60" (keyup)="searching($event)">
And component
searching(event:any){
console.log("routing");
this.router.navigateByUrl('/search/' + event.target.value );
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrey Etumyan |
| Solution 2 | Phạm Cưá»ng |
