Let's say that you have a "Product" business object and a "Products" page that show the list of available products. You want to add a search field that will automatically update the search results as the user types.
Set Products to Read Automatically
Add an array of Products called products:
Add searchString and Search Method
Add a property named searchString. Add a method to your user interface named "search" with this implementation:
let where = {
name: {
ilike: '%' + this.searchString + '%'
}
};
this.products.setOption('where', where);
this.products.read();
This where filter is set to do a case insensitive search of the name property on the products.
Add a Search Field
Add a Form Field containing an input field linked to the searchString:
Add a search icon after the input with the mat-prefix attribute:
Trigger Search
Update the searchString property to trigger the search method when it changes:
This will work but it causes a search to be made for each character the user types. Let's not put all that unnecessary load on our server and the user's internet connection.
Upgrade to Search After Pause
Add a property searchTimeout of type any. Add a method called startSearchCountdown with this implementation:
// If we were already counting down, cancel it
if (this.searchTimeout) {
clearTimeout(this.searchTimeout);
this.searchTimeout = null;
}
// Start the countdown
this.searchTimeout = setTimeout(
() => {
// The countdown ended, trigger the search
this.search();
this.searchTimeout = null;
},
500 // 500 milliseconds
);
Update the searchString to trigger the startSearchCountdown instead of start search. Now the search method will be called after an inactivity of 500 ms.