Implementing Auto-Suggestion in Input Field in Angular Template-Driven Forms
Template-driven forms in Angular offer a simple and declarative way to handle form creation and validation. In this article, we'll explore how to create a template-driven form with an input field that supports auto-suggestions. We'll use dummy data for demonstration purposes, but the same logic can be extended to fetch suggestions dynamically from an API.
Features
Input field for typing values.
Dropdown list of suggestions based on the user's input.
Ability to select a suggestion or continue typing.
Implementation Steps
1. HTML Template
We'll create an input field bound to ngModel
for two-way data binding and display a dropdown of suggestions when the user types.
2. Component Logic
The component will handle the business logic for filtering suggestions and updating the model when a suggestion is selected.
3. Explanation of Logic
Text Input: The input field uses
[(ngModel)]
for two-way binding withpackageNameModel
.Dropdown Display: The dropdown list is displayed conditionally based on whether suggestions are available (
showSuggestions
).Filtering Suggestions: The
onInputChange()
method filters the list of suggestions based on the user's input, ignoring case.Selecting a Suggestion: Clicking a suggestion updates the input value and hides the dropdown.
Enhancements
Dynamic Suggestions: Replace the
allSuggestions
array with an API call to fetch suggestions dynamically.Keyboard Navigation: Add support for keyboard navigation (e.g., arrow keys) within the dropdown.
Styling: Customize the dropdown's appearance to match your application's design.
Conclusion
Using template-driven forms, we created a simple and intuitive interface for typing and selecting values. This functionality can be used in various scenarios, such as search bars, autocomplete fields, and more.
Feel free to extend this example based on your project requirements!
Last updated