Introduction
In Angular, there are several ways to bind data to the view, including text interpolation, property binding, class/style bindings, and event binding. In this article, we’ll cover the basics of these bindings.
In an Angular template, a binding creates a live connection between a part of the UI created from a template(a DOM element, directive, or component) and the model(the component instance to which the template belongs). This connection can be used to synchronize the view with the model, to notify the model when an event or user action takes place in the view, or both. Angular’s Change Detection algorithm is responsible for keeping the view and the model in sync.
Text interpolation
Text interpolation refers to embedding expressions into marked up text, Angular use {{}}
to interpolate expressions into HTML.
Suppose you have a variable name
in the component, you can use it in the template like this:
1 | <p>Hello, {{name}}!</p> |
Or if you want to display an image based on its URL, you can do this:
1 | <img src="{{imageUrl}}" alt="image"> |
You can also use conditional expressions in text interpolation, for example:
1 | <div>Performance: {{ score > 90 ? 'Exceeded' : 'Match' }}</div> |
Or even a function call:
1 | <div>Performance: {{ getPerformance() }}</div> |
Note: text interpolation only works on string
, for all other types, Angular will first convert it to string then interpolate it.
Property binding
Property binding in Angular helps you set values for properties of HTML elements or directives.
Property binding moves a value in one direction, from a component’s property into a target element property. In the following example, the src
property of the img
element is bound to the imageUrl
property of the component.
Property binding syntax
You should enclose the HTML element property with []
, and put the component’s property in ""
. In this way angular will parse the content in quotes as a variable. the following code won’t work, since angular will treat imageUrl
as a literal string, not a variable in component.
1 | <img src="imageUrl" alt="image"> |
Text interpolation can also be used interchangeably with property binding, the following code has the same effects.
1 | <img src="{{imageUrl}}" alt="image"> |
So, if imageUrl
is an variable in component class, then[src]="imageUrl"
is equal to src="{{imageUrl}}"
.
Class/Style bindings
Class bindings
If you only need single class/style binding, you can use the following syntax.
Where grade
is a variable in the component, and this works as long as grade
is a truthy value.
1 | <div [class.grade]="grade">Student A</div> |
class bindings works the same as ngClass
directive, see here for details.
Style bindings
Style bindings works like class bindings, see here, we rarely use style bindings, since we always put styles into a single file, but its good to know.