Angular “Two-Way” Binding

In the previous several posts, we have looked at three types of binding (interpolation, property and event). In interpolation and property binding, the communication flows one way…from class to template. That direction when combined with Angular’s change detection allows you to programmatically update the class and change information that then gets updated in the template view. In event binding, the communication flow comes from the template to the class. In other word, when the end user triggers an event, then some method runs. But what about two-way? Angular provides what I, personally, call quasi-two-way binding. Two-way binding can be achieves by combining property and event binding with the “banana in a box” method.

Angular provides a directive (ngModel) to achieve two-way data binding. You start with importing the FormsModule and then you can create your two-way binding with ngModel as follows…imagine you have the following class…

export class AppComponent {
    dessert = 'chocolate ice cream';

We can set up two way data binding with form inputs as follows…

<!-- input for user to provide their own dessert -->
<input type="text" [(ngModel)]='dessert'>
<!-- the end users dessert will display here -->
<p>My favorite dessert is {{dessert}}</p>

The special notation using [(ngModel)] is called the “banana in a box” notation. I guess because someone thought that the parentheses looked like a banana and the square brackets look like a box…I dunno. But it combines property and event binding notation. So whenever the end user updates the input, the dessert property gets notified and changed, then the template view gets updated.

Happy Coding!

Clay Hess

Share this post

Share on facebook
Share on google
Share on twitter
Share on linkedin
Share on pinterest
Share on print
Share on email
Skip to content