AngularJS2 template syntax

In the previous chapters we have come into contact with the Angular template, we will introduce the syntax of Angular.
The template plays the role of a view, simply speaking is to show the user to see the part.
  • HTML
  • Interpolation expression
  • Template expression
  • Template statement
  • Binding syntax
  • Attribute binding
  • HTML attribute, class and style binding
  • Event binding
  • Use NgModel for bidirectional data binding
  • Built-in instructions
  • * With <template>
  • Template reference variable
  • Input and output attributes
  • Template expression operator

HTML

HTML is the "language" of the Angular template, except that the <script> element is disabled, and other HTML elements are supported, for example:
< H1 > my first Angular application </ h1 >

Interpolation expression

The syntax of the interpolation expression is: {{...}} .
Interpolation expressions can be written into the HTML string can also be used as a property value.
< H3 > {{title}} < img src = " {{imageUrl}} " style = " height: 30px " > </ h3 >

Template expression

{{...}} is actually a template expression, Angular evaluates it and converts it into a string output.
The following example is the sum of two numbers:
<! - "The sum of 1 + 1 is 2" -> < p > The sum of 1 + 1 is {{1 + 1}} </ p >
Can I use getVal () to get the value of this expression:
< Div class = " Example " > < div class = " example_code " > [mycode3 type = "HTML"] <-! ". 4" -> < P > {{getVal +. 1. 1 + ()}} </ P >
Template expressions are similar to JavaScript's language, and many JavaScript expressions are also legitimate template expressions, but not all.
The following JavaScript expression is forbidden:
  • Assignment expression =( +=, , -=...)
  • New operator
  • With ;or as 'a connection expression
  • Self- increasing and self- decreasing operations ( ++and --) Other noteworthy with Javascript syntax include:
  • Do not support bitwise operators ( |and &)
  • The expression of the template operator, such as |and ?.so on, is given a new meaning

Attribute binding

The attribute binding of a template can set the properties of the view element to a template expression.
The most common attribute binding is to set the attribute of the element to the value of the attribute in the component. In the following example, the src attribute of the image element is bound to the component's imageUrl property:
< Img [ src ] = " imageUrl " >
Disable a button when the component is isUnchanged:
< Button [ disabled ] = " isUnchanged " > button is disabled </ button >
Set the properties of the instruction:
< Div [ ngClass ] = " classes " > [ngClass] bound to the classes attribute </ div >
Set the properties of a custom component (this is an important way for communication between parent and child components):
< User-detail [ user ] = " currentUser " > </ user-detail >

HTML attribute, class and style binding

Template syntax provides a unique one-way data binding for scenarios that are less suitable for using attribute bindings.

Attribute, binding

When the element has no attributes can be tied, the use of HTML tag attributes (Attribute) binding.
Consider the attributes such as colspan / rowspan in ARIA, SVG, and table. They are pure attributes. They do not have the corresponding attributes available for binding.
The following example will be given:
< Tr > < td colspan = " {{1 + 1}} " > Three-Four </ td > </ tr >
We will get this error:
Template parse errors : Can 't bind to' colspan 'since it isn' ta known native property
 

Template parsing error: can not bind to 'colspan' because it is not a known native attribute
As stated in tips, <td>element has no colspanattributes. But interpolation expression and binding properties can only set the property , rather than Attribute, so HTML tags Attribute bindings need to create and bind similar Attribute.
The HTML tag attribute is syntactically similar to the attribute binding, but the part of the brackets is not the attribute name of an element, but consists of an attr. Prefix and the name of the HTML tag attribute, and then through a value of String expression to set the value of the HTML tag attribute. 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 CSS class binding, we can add and remove CSS class names from the element's class attribute.
CSS class binding is syntactically similar to attribute binding. But the part of the square brackets is not an element of the attribute name, but includes a class prefix, followed by a point (.), Followed by the name of the CSS class. The latter two are optional. For example: [class.class-name] .
The following example shows how to add and remove the "special" class via the css class binding class:
<! - standard HTML style class settings -> < div class = " Bad Curly Special " > of Bad Curly Special </ div > <! - by resetting or covering binding style class -> < div class = " Curly special Bad " [ class ] = " badCurly " > of Bad Curly </ div > <-! be added or removed by a special style class attribute value -> < div [ class . special ] = "IsSpecial " > this style is special </ div >

Style style binding

By style binding, you can set the inline style. Style binding syntax is similar to the property binding, but the brackets inside the part is not an element of the property name, style binding, including a style., Followed by css style attribute name, for example: [style.style-property] The
< Button [ style . Color ] = " ? IsSpecial 'Red': 'Green' " > Red </ Button > < Button [ style . Background-Color ] = " canSave 'Cyan':? 'Gray' " > save </ the Button > ! <- style units with bindings -> < the Button [ style . font-size . EM ] = " isSpecial 3: 1? " >Large </ button > < button [ style . Font-size .%] = " ! IsSpecial? 150: 50 " > small </ button >
The style attribute can be either the font-size or the hump is the font name (fontSize).

Event binding

In event binding, Angular responds to the corresponding data flow by listening to user actions, such as keyboard events, mouse events, touchscreen events, etc. - from the view target to the data source.
Event binding syntax is from the inside of the left side of the equal sign parentheses target event and right quotation marks in the template declaration composition.
For example, the following example is the event event of the event binding monitor button. As long as you click the mouse, the component 's onSave () method is called .
< 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's click event.
< Button ( click ) = " onSave () " > Save </ button >
You can also use the on-prefix form:
< Button on-click = " onSave () " > On Save </ button >

Use NgModel for bidirectional data binding

When developing a data entry form, the desired result is that both the component's data is displayed on the form and the component's data can be updated when the user changes it.
The following is a two-way binding through [(NgModel)] :
< Input [( ngModel )] = " currentUser.firstName " >
[] To achieve a data flow from the component to the template, () to achieve the data flow from the template to the component, both a combination of [()] to achieve a two-way binding.
Use the syntax of the prefix form:
< Input bindon-ngModel = " currentUser.firstName " >

Built-in instructions

Angular's built-in instructions are NgClass, NgStyle, NgIf, NgFor, NgSwitch, and so on.

NgClass

Dynamically add or remove CSS classes by binding to NgClass.
< Div [ style . Font-size ] = " isSpecial? 'X-large': 'smaller' ' > This div is large. </ Div >

NgStyle

NgStyle by binding it to a key: value control the form of the object, you can let us set a lot of inline style at the same time.
Settyles () {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;}
Add a NgStyle property by adding it to setStyles and set the style of the element:
< Div [ ngStyle ] = " setStyles () " > The div style is italic, normal weight, and extra large (24px). </ Div >

NgIf

By binding the NgIf instruction to a true expression, you can add an element and its child elements to the DOM tree.
< Div * ngIf = " currentUser " > Hello, {{currentUser.firstName}} </ div >
Instead, binding to a false-valued expression removes the element and its child elements from the DOM tree. Such as:
<! - because the value of isActive is false, so User Detail is not in the DOM tree -> < user-detail * ngIf = " isActive " > </ user-detail >

NgSwitch

NgSwitch is required when you need to display one of the possible elements from a set of possible elements. Angular will only add the selected element to the DOM. Such as:
< Span [ ngSwitch ] = " the userName " > < span * ngSwitchCase = " 'John Doe' " > John Doe </ span > < span * ngSwitchCase = ' ' John Doe ' " > John Doe </ span > < span * ngSwitchCase = " King five" " > Wang five </ span > <span * ngSwitchCase = " 'Zhao six' " > Zhao six </ span > < span * ngSwitchDefault > Lung Large </ span > </ span >
NgSwitchBinds the parent instruction to an expression that returns a value that is a string, but it can be any type of value. The parent directive NgSwitchcontrols a set of <span>child elements. Each <span>or on an expression that matches the value, or is marked as the default. At any time, only one of these spans will appear in the DOM. If the match value of the span is equal to the value of the switch, Angular2 adds this to the <span>DOM. If there is no span matching, Angular2 will add the default span to the DOM. Angular2 will remove and destroy all other span.
Three mutually directed instructions:
  • NgSwitch: An expression that binds to a return value
  • NgSwitchCase: binds to an expression that returns a matching value
  • NgSwitchDefault: a property used to mark the default element. Note: Do not use ngSwitch before *, but should be bound by attributes, but ngSwitchCase and ngSwitchDefault are put *before.

NgFor

This instruction is required when it is necessary to display a list of multiple entries. The following example is the application of NgFor on an HTML block.
< 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 >
The ngFor instruction supports an optional index index that grows from 0 to the length in the array during the iteration.
You can use the template input variables to capture the index, and applied to the template. The following example takes the index into a variable named i.
< Div * ngFor = " let user of users; let i = index " > {{i + 1}} - {{user.fullName}} </ div >

NgForTrackBy

The ngFor instruction sometimes performs poorly, especially in large lists. A little change, remove, or add to an entry can result in a cascading DOM operation.
For example, when you refresh the contacts by re-starting from the server, the refreshed list may contain many, if not all, of the previously displayed contacts. But in Angular's view, it does not know what it was before, clean up the old list, discard those DOM elements, and rebuild a new list with the new DOM element.
To solve this problem, you can use the tracking function to avoid this kind of toss. The trace function tells Angular: we know that two objects with the same user.id are the same contact. Such as:
TrackByUsers (index: number, user: User) {return user.id}
Then, set the NgForTrackBy directive to that trace function:
< Div * ngFor = " let user of users; trackBy: trackByUsers " > ({{user.id}}) {{user.fullName}} </ div >
The tracking function does not exclude all DOM changes. If used to determine whether the same contact for the property changes, it will update the DOM element, and vice versa will leave the DOM element. The list interface will become more smooth, with better response.

Template reference variable

A template reference variable is a reference to a DOM element or instruction in a template.
It can be used in native DOM elements and can also be used with Angular components - in fact, it can work with any custom Web component.
We can reference a template reference variable in the same element, a 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 handler -> < input # phone placeholder = " phone number " > < button ( click ) = " callPhone (phone.value) " > Call < / Button > <! - fax references the input element and passes `value` to the event handler -> < input ref-fax placeholder = " fax number " > < button ( click ) = " callFax (fax.Value " > Fax </ button >
The "#" prefix of "phone" means that we are going to define a phone variable.

related articles

Https://gf-rd.gitbooks.io/angular-2-step-by-step/content/chapters/2.3.html


EmoticonEmoticon