At the core of Template
is the way model values are bound to different parts of the element tree defined by the template.
To get started with using templates and learn how to set model values, see Creating A Simple Component Using the Template API.
The value of a model property can be used as the text content of an element using {{propertyName}}
inside a tag.
<div>
Hello, <span class="greeting-name">{{name}}</span>
</div>
You can set an element property value based on a model by using the special [propertyName]="binding"
syntax.
The next example creates an image link where the linkTarget
property from the model us used as the link target and the image
property is used as the image URL.
<a [href]="linkTarget">
<img [src]="image">
</a>
Warning
|
[name]="binding" defines that the element property named name should get it’s value from the model property named binding , whereas name="binding" (i.e. without brackets) defines that the element attribute named name should have the value binding regardless of any value in the model.
|
A binding written as <div [something]="model"></div>
is bound to the property something
because the property can typically be changed on the fly while the attribute is often used only for the initial value.
When you what to explicitly bind to an attribute, you prefix the name with attr.
, i.e. write <div [attr.something]="model"></div>
to bind to the attribute something
.
Note
|
Many elements require you to use the property instead of the attribute to be able to update the value. It is usually best to use the property binding [something] unless the element specifically defines that you must use an attribute.
|
There is special support for binding class names in a template, see Binding Class Names in a Template.
Bindings are not limited to binding to a part of the model but can be any valid JavaScript expression. This can be useful for e.g. formatting text
Username: <span>{{firstName.toLowerCase() + "@example.com"}}</div>
JavaScript can also be used for really simple logic in a template binding, like hiding an element if there are no items:
<div [class.hidden]="itemCount == 0">Items available: {{itemCount}}</div>
Note
|
More complex logic is usually much more manageable if written outside the binding. |
Note
|
The binding will be evaluated as JavaScript both on the server and on the client so do not rely on browser API being available. |