I have created a database using SQL and I have a functional web page built on Angular and nodejs which is connected to the database. I need to make the search bar functional. How should I proceed?
Advertisement
Answer
Create a input box in html with keyup event as :
x
<input (keyup)="searchData($event)" type="text" class="form-control" placeholder="Search"
aria-label="Searchbox" aria-describedby="basic-addon1">
Add this function in your .ts file which will be triggered on keyup in search box :
searchData(event) {
this.search = event.target.value
console.log(this.search)
console.log(this.filter)
this.empService.searchData(this.search).subscribe((res) => {
console.log("Filter Response", res);
if (res) {
this.employees = res
if (res.length === 0) {
this.noData = true
} else {
this.noData = false
}
}
},
(err) => {
console.log(err);
console.log("error")
})
}
Create a service to call your api in node :
searchData(data): Observable<any> {
return this.http.get(environment.serverUrl + 'searchData?search=' + data).pipe(
catchError((error: HttpErrorResponse) => throwError(error))
)
}
Write a api in node as :
let searchData = (req, res) => {
search = req.query.search
console.log(search)
var searchEmployees = `SELECT * FROM employees WHERE (employeeNo LIKE '%${search}%' OR name LIKE '%${search}%' OR email LIKE '%${search}%' OR contact LIKE '%${search}%') AND isDeleted='0' `
//searchValues = [search,search,search,search]
console.log(searchEmployees)
db.query(searchEmployees, function (errQuery, resQuery) {
if (errQuery) {
res.send(errQuery)
} else {
res.send(resQuery)
}
})
}
Edit sql query as per your table structure and name.