Angular 2 introduce a new powerful data binding syntax, that you can use in the application views.
With this new features, you can specify for every element if it’s binded one way (property, function) or two way (model update).
The new sintax is very clear and once you understand is very easy to use it in the application views.
One way
This binding can allow you to bind a property or a function.
You can use a property when you want to show a value from the model in the view, or a function when, for example, you want to fire an event once the user make an action.
<input [ngModel]="person.FirstName" />
This is one way binding for a property.
In Angular 2, when you want to bind a DOM element to a property or function, you need to use ngModel directive; note that ngModel is enclosed in square brackets, which indicates a one way binding; therefore, when the value in the field will be updated, this value will not be reflected in the model.
Another possible syntax is with curly brackets:
<label>{{person.FirstName}}</label>
Binding an event is slightly different:
<input type="button" value="delete" (click)="delete(person)" *ngIf="person.Id!=0" />
This is a binding for a click event; once the user click the button, the delete function in the controller will be fired.
Two way
You can use this data binding when you want each update on view is reflected in the model.
<input [(ngModel)]="person.FirstName" />
In this case, the ngModel directive is enclosed in [()] that means two way data binding.
Every time the value will be changed in the DOM element, it’ll be reflected in the model as well as when the value will be changed in the model, it will be showed in the view.
Leave a Reply