Angular 2 - Property binding
Another way you combine data in
templates with Angular is through property binding. HTML elements
have backing Dom
properties that track state on elements.
You can use Angular's
property binding syntax to wire into those properties. You do this
with a specific syntax, a pair of square brackets around a property
name on an element, and you set these equal to a template expression
following the same rules as you do for interpolation.
So, in the media-item.component.html
file let's add a text content property to the h tag which is a native
Dom property for tracking text
content in an element. Then we surround it with square brackets and
set it equal to the name expression context property.
In media-item.component.html
<h2
[textContent]=”name”> </h2>
<div>Watched on
1/13/2016</div>
<div>Action</div>
<div>2016</div>
<div class="tools"></div>
Now we can remove the interpolation
statement from within the h tag. And when we switch over to the
browser we see we have the same result. Using the property binding
syntax of the square brackets, tells Angular that you want it to evaluate
an expression for that property. If we leave off the brackets, and we
switch back over to the reloaded browser, we see that nothing gets
rendered for the title. This is because
Angular is not evaluating the
quoted value as an expression. But, if we put the interpolation curly
braces around the property name, and switch back over to the browser,
we can see that Angular will then process it. And, actually, Angular will
translate the interpolation approach into the same property
binding that the previous syntax did. So we can do property binding
either way.