Autocomplete Typeahead Suggestions Search in Angular 9 application
Nowadays, most of web or mobile applications are using typeahead search rapidly in their application and there are many libraries that are built over time, and believe me, those are working great. But there is always a need for some customization and then using the library to sort out problems will be a pain for the developer as well as for the business.
Many of us have a question "What is the difference between Autocomplete search and Typeahead search?". And the answer is both are the same. The jquery developers are calling it Autocomplete and Twitter developers are calling it Typeahead. Sometimes it is also called the Suggestions Search Bar.
The typeahead search is required when we have a large number of data and that can not be accomodate in dropdown menu. To simplify the UI/UX, typeahead search idea had implemented a long back. It has a simple input field and whatever user type on it, the data set will filter it and display it to the end user.
There are several open-source examples out there like -
But in this blog, let's create it by ourselveswithout using any librarywhich is specific to typeahead. It will reduce your bundle size by at least a few bites. First, have a look at how it works -
Step 1: First create a boolean property to show and hide the search option.
Using this, you can get rid of the following error -
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'disabled: undefined'. Current value: 'disabled: true'.
Step 2: Add the TypeAheadComponent in dynamic manner using ComponentFactoryResolver
If you use the dynamic manner, the component will be enabled, if the user wants to use the search options or not.
The benefit of dynamically adding component:The component will not be fixed, it will add to the DOM whenever it is required and once the work is done it will get removed from the DOM as well. For more information about the dynamic loading component you can follow the angular tutorial.
Step 3: Pass the data source to the search component
You should use the data source to be deep copied before passing the value to the search component so that your original object will not be changed.
const searchDataSource = this.searchDataSource.map(item => Object.assign({}, item)); // deep copy
Step 4: TypeaheadComponet should subscribe to the user selection and respond back to the parent component
Once, a user selects the search item, the respective object must be sent to the parent component using the @output decorator. So, the parent component can get the selected object and do the respective work to perform.
Demo Time:
The complete code has been created without using any CSS library, for good user experience and responsive nature bootstrap, material bootstrap, etc can be used and improve the user experience.
Loading comments...