Introduction
In earlier post, we saw how to communicate in and out of components using input/output properties.
Another approach we learned was use of template reference variable and @ViewChild decorator to access elements/components on template and call methods on it. You can check this article for details.
Today, we’ll learn how to notify the component of user changes. We can use following for this purpose:
- Two-way bindings (long-form)
- Getter/Setter
- valueChanges observable
We’ll cover the first two in today’s post.
Initial Setup
I’ve setup some initial component and HTML for example
The generated view is as follows
Search Input
For filter input following input element is bind to listFilter property using short style for binding.
This will render an Input box for search entry and entry will be displayed inside a <p> tag.
Two-Binding (Long-form)
Following is the markup for typical two-way binding (short style) with input where user can enter some filter criteria.
Two-way Data Binding (short-form)
so, the listFilter property will be updated with the user input, but how to actually perform filtering operation?
To notify the component and perform some additional operation beside simple data-binding (i.e. actually perform filter) We can use long-form.
Two-way Data Binding (long-form)
But now, we have to set listFilter property ourselves in onFilterChange method (Coz we’ve lost the two-way binding in long-form)
but with two-way long form, we can actually call a method (e.g. performFilter()) to perform the filter.
So, we can use this technique to react to user input and perform some operations.
Let’s see next Getter/Setters to achieve similar results.
Getter/Setters Way
Following shows typical property declaration in our component. Our component can bind it to it using familiar short style two-way binding syntax.
and following is the getter/setter way (notice one line becomes -> 8 lines)
As you can see that this style also allow us to perform some actions based on user input.
However, this is sometimes preferred over two-way binding (long-form).
Following is the performFilter()
code for your reference
and following is output with filter applied
Summary
In this post, we saw the basic techniques to notify the component of user changes (e.g. user enters a filter criteria and expect to see a filtered list of items). Another, similar example would be to filter the list based on drop-down item selection and the likes.
We saw examples of two-way binding (long form) and by use of get/set operations for the property.
You can download the source code from this git repository.
The deployed sample application is available on this URL.
Let me know if you have some questions and/or comments. Till next time, Happy Coding!
Discover more from Hex Quote
Subscribe to get the latest posts sent to your email.