In early July I started to re-develop my latest project with Blazor. I would say, I learned lots of things about Blazor with this project. In this article, I have tried to explain ‘how to make two way binding in Blazor‘
First of all, when do we use two way binding? We use two way binding for communication between components. (It’s mean data-related) In my example, I have used two components. Those components are Calculate Form and Result Table. When application had started, I called calculate form with an empty Response model. In this example, users don’t see the result table component during the response model empty. After users fill out the form and click to Calculate Button I calculate the result and fill the response object. At this point I should use a two way binding to show the result object. Let’s see my example codes.
First screenshot is from my calculator page. I call my components on this page. The screenshot for this page is as follows.
In this screenshot, you can see one way and two way binding together. In the first component (CalculateForm) I used two way binding. If you use two way binding, you should define it like @bind-VariableName=”Value” The second (ResultTable) is an example for one way binding. You should define it like VariableName=”Value” After this step, let’s check the first Result Table object. How it’s working and triggering. As follows code from ResultTable object.
I have defined my VariableName as a parameter inside of the component. Parameter tag is must for one way binding and parameter name should be the same as screenshot 1. At this component I checked if this parameter is null, I don’t show anything. When I send a filled parameter to this object, people will see this html. My last screenshot is as follows.
In this component, I defined a variable which is the same type with my two way bind parameter. I am going to check changes with this value. After this, I added my variable as a parameter but it’s different from the result table’s one and I defined EventCallBack object at end of the my component. In this component, I check my parameter, when It changes, I called my event callback object and updated my parameter on the main page and I showed the result component to users. If I had used one way binding in this component too, I couldn’t update my object on the main page and I couldn’t show the result table component to users.
I tried to explain two way binding (maybe included one way binding) in this post. Hopefully It works. See you on next posts.
Note: This blog is like a notebook for myself. If you see anything wrong, you can contact me via this blog.