This article on Data Binding is part of the Learning Angular series.
DataBinding is required for communications between the client and the server.
To output data, one can use:
- String Interpolation – {{ data }}
- Property Binding – [property]=”data”
To react to user interactions
- Event Binding – (event)=”expression”
While the above ways are 1-way binding, angualr can be used for 2-way binding by combining the above:
[(ngModel)]=”data”
String Interpolation
The string interpolation can be done by wrapping the expression between double curly braces –
{{ expression }}
The expression can be anything which will return a string, or can be converted to a string, but not multi levels of code. It can be:
- A variable name – {{ userName }}
- A direct string – {{ ‘my name is Anthony’ }}
- A function which would return a string – getUserName() – A function which would be returning a string
- Ternary operations – userName ? userName : ‘anonymous’
One can find more about String Interpolation on Angular Guide.
Property Binding
Every HTML element has a lot of properties, but not all can be accessed/set via the attributes.
For example, ‘disabled’ is an attribute which when set disables the element. But this is also a property which can be accessed using the [disabled] in the HTML tag and can be used as a property to set.
<button class="btn" disabled>Click Me</button> Setting the attribute 'disabled' <button class="btn" [disabled]="true">Click Me</button> Setting the property 'disabled'
Property Binding vs String Interpolation
Use string interpolation when we have to show some text only.
Use property binding, when there is requirement to bind the property of an element to some variable.
Event Binding
Events can be bound in Angular using the moon brackets.
(click)=”myFunction()” will call the myFunction() available in the .ts file.
Don’t bind to onclick. This is for javascript and not Angular.
Bindable properties and events
A console.log() on the element will provide the events available for binding.
Passing and Using Data with Event Binding
The event data can also be passed on to the function using the $event reserved keyword.
Usage:
<input type="text" (input)="onUpdateServerName($event)">
This will pass the event data to the function and can be used in the following way:
onUpdateServerName(event:Event) { this.serverName = (event.target).value; // The (event.target) is the way to typecast to make sure that the compiler doesn't throw compiling error. }
Two Way Data-Binding
Two Way Binding can be implemented combining the square brackets as well as the moon brackets.
Usage:
<input type="text" [(ngModel)]="serverName">
Important Notice for Two-Way Data-binding
For Two-Way Data-binding to work, make sure to import the FormsModule from ‘@angular/forms’ in the app.module.ts, and add it to the imports array.