[Angular Tutorial] - 03 - Two-way data binding and Template #ref variables

In this post, I'm going to show you how to use two-way binding in Angular 2+ and also template #ref variable which is quite interesting.

Two-way binding

If you have had experience of AngularJS (Angular 1) you may know about ng-model and two-way binding as well.

In the previous angular tutorial post, I have shown you how to bind data to template (INPUT, DIV,...) and how to update data for INPUT using one-way data binding via DOM event like on-change. Now I'm going to show you another approach to update value of form element like INPUT or SELECT using two-way data binding.

One-way data binding

<input type="text" (change)="onChange($event.target.value)" [value]="name" />  

Two-way data binding

<input type="text" [(ngModel)]="name" />  

It's very simple and we don't need to handle any TypeScript code in the component class. When you update value in the INPUT, that value will be updated to the model.

But in some case we want more than that, we want to transform the value before update model in component or apply some logic at the time the model has been updated. Angular provide ngModelChange to help we solve this matter.

<input type="text" [ngModel]="name" (ngModelChange)="onChange($event)" />  

So now what you need to do is create onChange in component class and $event here is the updated value of the INPUT.

In order to get ngModel directive work we need to import FormModule module from @angular/forms.

import { FormModule } from '@angular/forms';  

Template #ref variables

A #ref variable will be represent a DOM element in the html template. We can get value (of INPUT) or text (of DIV, SPAN) of an element.

<input type="text" [(ngModel)]="name" #username />  
<p>{{username.value}}</p>  

As you can see #username represent for the INPUT DOM element and we can get value of this INPUT via username variable.

You can try by yourself below:

Cheers,
Happy learning Angular!

Nguyen Tran

I'm Nguyen, a full stack web passion for frontend and love Angular.

Subscribe to Nguyen Tran

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!