Sometimes we want to bind a value in an element with a property in the component and also have the element’s onchange event trigger a method in the component. Why would we want to do this? Because sometimes we need to save the user’s input and also use it to do something else like filter a list or trigger a method in the parent component.
To both bind to a property and call a method with the onchange event, the first solution that comes to mind is to bind the element’s value to a property and also assign a method to the onchange event. However this doesn’t work because the onchange event cannot be assigned to more than one method. Intellisense complains with the message “The attribute “onchange” is used two or more times for this element. ..”.
One solution is to create a backer property and call the component’s method (HandleValueChanged in the example) in the properties set method as shown below.
Another approach is to one-way bind to the element’s value with (value=@MyProperty) and also assign the callback method to the onchange event with (@onchanged=HandleValueChanged) as shown here.
If you want to two-way bind with a property in the parent and trigger a method in the parent on a value change then add two EventCallback type parameters to the component. One for implementing the two-way binding which will need to be named the same as the component’s property name along with the suffix “Changed”, so in our example the name would be MyPropertyChanged. The second EventCallback parameter can have any name however to conform to how the HTML element attributes are named the name OnChange would be my suggestion. Then invoke the callback methods in the property setter or in the method call depending on which approach you took. Here’s an example of the second approach.