Angular - 2.18 Bidirectional data link

In the last few videos, we learned a lot about linking events and linking properties. Now we’re going to combine the two to get a two-way connection. We have learned that we can get data from an event this way, but there is also another approach.

If I copy this and comment on it and replace this input event with something else, you will see that we have an even easier way to link to certain data. With bidirectional data linking, we combine the linking of properties and events. So we use it by combining the syntaxes, in brackets, and within those parentheses.

Now, here, we need to use a special directive, and we’ll learn more about the NgModel directives in a moment. Now we can set this equal to a property defined in our TypeScript code. For example, the serverName. This configuration will do the following. It will trigger on the input event and update the serverName value in our component automatically.

On the other hand, since this is a bidirectional link, it will also update the input element value if we change the serverName somewhere else. And I can demonstrate that, by going back to the TypeScript code and setting the serverName to the test server here initially. It was an empty string, now it’s not.

With this, if we go back to the running application, you see that the input is pre-filled with this. Now, if for demonstration purposes I comment in the other input that does not use a bidirectional link, you see that this input is empty because again it does not use a bidirectional link.

Now, if I type something here, you see that it updates the property name and so it updates it here where we use the interpolation string, and in the other input. But if I type here, it won’t be changed in the first input because, again, we don’t use the bidirectional link here.

This is what bidirectional data binding is, a very simple way to link back and forth and, for example, react to changes in the input value here. So I’m going to comment on the first approach. I’m going to leave it to the method even though we don’t call it anymore. But with this, you now have a glimpse of two-way liaison, a simple and effective way to react to events in both directions.

Now let’s refine our application a little bit here and then move on to directives, another essential feature of Angular.