Angular 2 template syntax
We have touched on the templates of Angular in the previous chapters, and in this article we will cover the syntax use of Angular in detail.
The template plays the role of a view, which is simply the part that is shown to the user.
HTML
Interpolation expression
Template expression
Template statement
Binding syntax
Property binding
HTML attribute,
class
andstyle
bindingEvent binding
Use
NgModel
perform two-way data bindingBuilt-in instruction
\ *
and<template>
Template reference variable
Input and output attributes
Template expression operator
HTML
HTML is the “language” of Angular templates, except <script>
elementsare disabled except for other elements HTML
elements are supported, such as:
<h1>My first Angular application</h1>
Interpolation expression
The syntax format of the interpolation expression is: {{ ... }}
.
The interpolation expression can insert the evaluated string into HTML, or it can be used as an attribute value.
<h3>
{{title}}
<img src="{{imageUrl}}" style="height:30px">
</h3>
Template expression
{{ ... }}
is actually a template expression that Angular evaluates and converts to string output.
The following example is the addition of two numbers:
<!--"The sum of 1 + 1 is 2"-->
<p>The sum of 1 + 1 is {{1 + 1}}</p>
We can use getVal()
to get the value of this expression:
<div class="example">
<div class="example_code">
[mycode3 type="html"]
<!-- "4" -->
<p>{{1 + 1 + getVal()}}</p>
Template expressions are similar to JavaScript’s language, and many JavaScript expressions are legal template expressions, but not all of them.
The following JavaScript expressions are prohibited:
Assignment expression(
=
,+=
,-=
…)New operator
With
;
or'
the connection expression ofSelf-increasing and self-subtracting operations (
++
and--
other noteworthy things that differ from Javascript syntax include:The bit operator is not supported
|
and&
)Operators for template expressions, such as
|
and?.
, etc., has been given a new meaning
Property binding
The attribute binding of the template can set the property of the view element to the template expression.
The most common attribute binding is to set the property of the element to the value of the property in the component. In the following example, image
of the element src
property will be bound to the component’s imageUrl
attribute:
<img[src]="imageUrl">
When the component is isUnchanged
disable a button when (unchanged):
<button[disabled]="isUnchanged">The button is disabled</button>
Set the properties of the instruction:
<div[ngClass]="classes">[ngClass]Bind to classes attribute</div>
Set the properties of a custom component (this is an important way to communicate between parent and child components):
<user-detail[user]="currentUser"></user-detail>
HTML attribute (Attribute), class
and style
binding
Template syntax provides a special form of one-way data binding for scenarios that are not suitable for attribute binding.
Attribute, binding
Use the HTML tag (Attribute) to bind when the element has no attributes to bind.
Consider ARIA, SVG, and table colspan/rowspan
etc. (Attribute). They are pure attributes. They have no corresponding properties to bind.
The following example will report an error:
<tr><tdcolspan="{{1 + 1}}">Three-Four</td></tr>
We will get this error:
Template parse errors:
Can't bind to 'colspan' since it isn't a known native property
Template parsing error: cannot bind to 'colspan' as it is not a known native property
As the hint says, <td>
element has no colspan
property. But interpolation expressions and property bindings can only set properties, not Attribute
, so the HTML tag is required Attribute
binding to createsomething similar to binding Attribute
.
The HTML tag feature binding is syntactically similar to attribute binding, but the part in square brackets is not the attribute name of an element, butis represented by a attr.
and the name of the HTML tag attribute, andthen set the value of the HTML tag attribute through an expression that evaluates to a string. Such as:
<table border=1>
<tr><td [attr.colspan]="1 + 1">One-Two</td></tr>
<tr><td>Five</td><td>Six</td></tr>
</table>
Css class binding
With the CSS class binding, we can derive from the element’s class
add and remove CSS class names on the.
CSS class binding is syntactically similar to property binding. But the part in square brackets is not the attribute name of an element, but includes a class prefix, followed by a dot. (.)
followed by the name of the CSS class The latter two parts are optional. For example: [class.class-name]
.
The following example shows how to add and remove the “special” class through the css class binding class:
<!-- Standard HTML Style Class Settings -->
<div class="bad curly special">Bad curly special</div>
<!-- By binding to reset or overwrite style classes -->
<div class="bad curly special" [class]="badCurly">Bad curly</div>
<!-- Add or remove special style classes through a property value -->
<div [class.special]="isSpecial">This style is quite unique</div>
style
style binding
With style binding, you can set inline styles. Style binding syntax is similar to attribute binding, but the part in square brackets is not the attribute name of an element, style binding includes a style.
followedby the property name of the css style, for example: [style.style-property]
.
<button [style.color] = "isSpecial ? 'red': 'green'">red</button>
<button [style.background-color]="canSave ? 'cyan': 'grey'" >Save</button>
<!-- Style binding with units -->
<button [style.font-size.em]="isSpecial ? 3 : 1" >big</button>
<button [style.font-size.%]="!isSpecial ? 150 : 50" >small</button>
Style attributes can be centerline naming (font-size) or hump naming (fontSize).
Event binding
In event binding, Angular responds to the corresponding data flow by listening for user actions, such as keyboard events, mouse events, touch screen events, and so on-from the view target to the data source.
The syntax for event binding consists of the target event in parentheses to the left of the equal sign and the template declaration in quotation marks on the right.
For example, the following example is the click event of the event binding listener button. Whenever you click the mouse, the component will be called.``onSave()`` method.
<button(click)="onSave()">Save</button>
The name in parentheses– such as (click)– marks the target event. In the following example, the target is the button click
events.
<button(click)="onSave()">Save</button>
You can also use the on-
form of prefix:
<buttonon-click="onSave()">On Save</button>
Use NgModel
perform two-way data binding
When developing a data entry form, the expected result is that you can both display the component’s data on the form and update the component’s data when the user modifies it.
The following is a pass [(NgModel)]
to implement two-way binding:
<input[(ngModel)]="currentUser.firstName">
[]
Realize the data flow from component to template ()
realizes the combination of data flow from template to component. [()]
Two-way binding is implemented.
Use syntax in the form of a prefix:
<inputbindon-ngModel="currentUser.firstName">
Built-in instruction
The built-in instructions for Angular are NgClass
、 NgStyle
、 NgIf
、 NgFor
、 NgSwitch
, etc.
NgClass
By binding to the NgClass
dynamically add or remove CSS classes.
<div [style.font-size]="isSpecial ? 'x-large' : 'smaller'" >
This div is in large size.
</div>
NgStyle
NgStyle
By binding it to a key:value
controlling the form of the object allows us to set many inline styles at the same time.
setStyles() {
let styles = {
// CSS Property Name
'font-style': this.canSave ? 'italic' : 'normal', // italic
'font-weight': !this.isUnchanged ? 'bold' : 'normal', // normal
'font-size': this.isSpecial ? '24px' : '8px', // 24px
};
return styles;
}
By adding a NgStyle
property binding, let it call the setStyles
and style the element accordingly
<div [ngStyle]="setStyles()">
The style of this div is italic, normal weight, and extra large (24px).
</div>
NgIf
By putting NgIf
directive binds to a truth expression that adds an element and its child elements to the DOM
in the tree.
<div\*ngIf="currentUser">Hello,{{currentUser.firstName}}</div>
Instead, binding to a false value expression will start from the DOM
removes the element and its child elements from the tree. Such as:
<!-- Because the value of isActive is false, User Detail is not in the DOM tree-->
<user-detail *ngIf="isActive"></user-detail>
NgSwitch
When you need to display one of them conditionally from a set of possible element trees, you need NgSwitch
. Angular will add only the selected elements to the DOM
. Such as:
<span [ngSwitch]="userName">
<span *ngSwitchCase="'Zhang San'">Zhang San</span>
<span *ngSwitchCase="'Li Si'">Li Si</span>
<span *ngSwitchCase="'Wang Wu'">Wang Wu</span>
<span *ngSwitchCase="'Zhao Liu'">Zhao Liu</span>
<span *ngSwitchDefault>Longda</span>
</span>
As a parent instruction NgSwitch
bind to an expression that returns a switch value, which in this case is a string, but it can be any type of value. Parent instruction NgSwitch
control a group <span>
child elements. Every one of them. <span>
is either hung on an expression that matches the value, or is marked as the default. At any time, these span
at most one of the will appear in DOM. If this span
the matching value is equal to the switch value, and Angular2 takes this <span>
add to DOM. If there are no span
on the match, Angular2 willset the default span
add to DOM. Angular2 removes and destroys all other span
.
Three directives for mutual cooperation:
ngSwitch
:Bind to an expression that returns a switch valuengSwitchCase
:Bind to an expression that returns a matching valuengSwitchDefault
attribute used to mark the default element Note: don’tngSwitch
pre-use*
instead, you should bind with properties, butngSwitchCase
andngSwitchDefault
to put it in the front.*
.
NgFor
This directive is required when you need to display a list of multiple items. As in the following example, it is applied to a HTML block NgFor
.
<div\*ngFor="let user of users">{{user.fullName}}</div>
NgFor
can also be applied to a component element, such as:
<user-detail\*ngFor="let user of users"[user]="user"></user-detail>
ngFor
directive supports an optional index
the index grows from 0 to the length of the array during the iteration.
You can capture this by entering variables from the template index
and apply it to the template The following example puts index
captured a man named i
in the variable.
<div *ngFor="let user of users; let i=index">{{i + 1}} - {{user.fullName}}</div>
NgForTrackBy
ngFor
instructions sometimes perform poorly, especially in large lists. A small change, removal, or addition to an entry can lead to cascading DOM
operation.
For example, when the address book is refreshed from the server, the refreshed list may contain many, if not all, previously displayed contacts. But in Angular’s view, it doesn’t know what has existed before, and can onlyclean up the old list and discard those. DOM
element and use the new DOM
element to recreate a new list.
To solve this problem, you can avoid this hassle by tracking functions. The tracking function tells Angular: we know that two have the same ``user.id``is with the same contact. Such as:
trackByUsers(index: number, user: User){return user.id}
Then, put NgForTrackBy
the instruction is set to that tracking function:
<div *ngFor="let user of users; trackBy:trackByUsers">({{user.id}}) {{user.fullName}}</div>
The tracking function does not exclude all DOM
change. If the attribute used to determine whether it is the same contact has changed, it will be updated DOM
element, otherwise it will leave this. DOM
element. The list interface becomes smoother and more responsive.
Template reference variable
The template reference variable is a reference to the DOM
a reference to an element or instruction.
It can be used in the original DOM
element and can also be used with Angular components– in fact, it works with any custom Web component.
We can reference template reference variables in the same element, sibling element, or any child element.
Here are two examples of creating and using template reference variables:
<!-- Phone references the input element and passes' value 'to the event handle -->
<input #phone placeholder="phone number">
<button (click)="callPhone(phone.value)">Call</button>
<!-- Fax references the input element and passes' value 'to the event handle -->
<input ref-fax placeholder="fax number">
<button (click)="callFax(fax.value)">Fax</button>
The (#) prefix of “phone” means we are going to define a phone
variable.