ANGULAR4-Template syntax

Source: Internet
Author: User
Tags emit export class

ANGULAR4-Template Syntax 1. Introduction to template Syntax HTML is the language of the angular template. Almost all HTML syntax is a valid template syntax. The notable exception, however, is the <script> element, which is disabled to prevent the risk of a script injection attack. (Actually,,<script> is just ignored.) )
It is meaningless to have some legitimate HTML to be used in a template. The You can extend the HTML vocabulary in a template through components and directives. They appear to be new elements and attributes.

So what is the template syntax?
For a simple HTML code, we can configure CSS properties within the page, bind events, and design the location of element elements to achieve the desired results. And so on to the angular template. The template syntax prescribes the following (self-summarizing):
* Defined HTML Vocabulary (script is ignored, html,body,base meaningless, extended instructions and components)
* Extended-interpolation expressions and extended template expressions
* Extended binding syntax (attribute binding, event binding syntax, and bidirectional binding content)
* Template reference variables (see component chapters)
*angular built-in directives (this chapter does not explain, follow instructions will be described in the article)
*angular Custom Directives (This chapter does not explain, the following instructions will be described in the article)


All in all, template syntax is a requirement for us to manipulate template content to achieve the results we want.
2. The interpolation expression and template expression (1) interpolation expression {{}} is called an interpolation expression, and the public variable in the current component controller can be directly evaluated and then displayed with its value.

I am {{employee.name}}}
Angular.component.ts
Export Class Angularcomponent implements OnInit {public
  employee:employee = {
    name : ' Rodchen ', company
    : ' Aug '
  }

  constructor () {
  }

  ngoninit (): void {
  }
}
An interpolation expression can also insert a computed string into an HTML element label or assign a property to a label
 
(2) template expressionA template expression produces a value. Angular executes this expression and assigns it to the property of the binding target, which may be an HTML element, component, or instruction

。 An interpolation expression is actually a template expression, except that we simply assign the variable value in the controller directly to the element. If a calculation occurs in {{}}, then we can call it a template expression. A template expression can be a numeric calculation
<p>the sum of 1 + 1 is {1 + 1}}</p>
It can also be a way to invoke the host component
<p>the sum of 1 + 1 is not {{1 + 1 + getval ()}}</p>
Template expressions look like JavaScript expressions, but there are some rules:

Expressions that have or may cause side effects in JavaScript are prohibited, including:
Assignment (=, + =, =, ...)
New operator
The chain expression used;
Self-increasing or self-subtraction operators (+ + and--)


Other notable differences from JavaScript syntax include:
bitwise operations Not Supported | and &
has a new template expression operator, such as a | 、?. And!.


(3) Template expression operator a) pipe operator (|)Before binding, the result of an expression might require some conversion. For example, you might want to display numbers as amounts, force text to uppercase, or filter lists and sort them.
I am {{employee.name | uppercase}}//i am Rodchen
Specific use can refer to pipe, there will be a special article to learn.
b The Safe navigation operator (?.) and the Null property pathAngular's safe navigation operator (?.) is a smooth and convenient way to protect the null and undefined values that appear in the property path. For example, in a), if the employee is NULL, what will happen to the page.
"I AM" will still render, but it will be an error.
We can then use the safe navigation operator to circumvent this error.
I am {{employee?. name | Uppercase}}
c) Non-null assertion operator (!)If the type inspector cannot determine whether a variable is null or undefined during run time, it also throws an error. We ourselves may know that it will not be empty, but the type checker does not know. So we're going to tell the type checker that it's not going to be empty, so we're going to use a Non-empty assertion operator.
The * * Non-NULL assertion operator (!) in the angular template is also used.
For example, after you have checked with *ngif that the hero is defined, you can assert that the Hero attribute must be defined.
src/app/app.component.html
 content_copy
<!--no hero, no text-->
<div *ngif= "Hero" >
  the Hero ' s name is {{hero!. Name}}
</div>
This operator prevents Typescript from reporting "hero.name may be null or undefined" errors when the angular compiler converts your template to Typescript code.
Unlike the safe navigation operators, a Non-empty assertion operator does not prevent null or undefined from appearing. It simply tells the typescript type Checker not to do "strict null detection" for a particular property expression.
If we turn on strict control detection, we need to use this template operator, and in other cases it is optional.
(4) Realization of interpolation expression
On the surface, we inserted the result between the element tags and assigned the properties of the label. This is convenient to think about, and this misunderstanding rarely brings us trouble. But strictly speaking, this is wrong. An interpolation expression is a special syntax that angular it into an attribute binding. Property bindings are said later.

3. Binding SyntaxData binding is a mechanism used to coordinate user-visible and applied data. While we can push values to HTML or pull values from HTML, applications can be easier to write, read, and maintain if you give them to the data-binding framework for processing. The framework completes this task simply by declaring the binding between the binding source and the target HTML element.
(1) binding type a one-way from data source to view target
Interpolation expression {{expression}}}
DOM Property Bindings [target]= "expression"
HTML Attribute Binding [attr.target]= "expression"
CSS class Bindings [class.class-name]= "expression"
Style bindings [target]= "expression"
b one-way from view target to data source
Event binding (target) = "statement"
c) Bidirectional binding
[(target)]= "expression"
(2) Comparison of HTML attribute and DOM propertyBefore introducing bindings, let's look at an important question: the contrast between HTML attribute and Dom property. To understand how angular binding works, it's important to know the difference between HTML attribute and Dom property.
attribute is defined by HTML. The property is defined by the DOM (Document Object Model).
A small number of HTML attributes and property have 1:1 mappings, such as IDs.
Some HTML attributes do not have corresponding property, such as colspan.
Some DOM property has no corresponding attribute, such as textcontent.
A lot of HTML attribute looks mapped to the property ... But it's not like we think.


Attribute initializes the DOM property, and their tasks are completed. The value of the property can be changed, and the value of attribute cannot be changed.

As an example:
<input type= "text" value= "name" (input) = "Onput ($event)" >
Import {Component, OnInit} from ' @angular/core ';

@Component ({
  selector: ' App-angular ',
  templateurl: './angular.component.html ',
  styleurls: ['./ Angular.component.css ']
})

Export class Angularcomponent implements OnInit {
  constructor () {
  }

  Ngoninit (): void {
  }

  onput (event) {
    Console.log (' DOM property: ' + Event.target.value);
    Console.log (' HTML attribute: ' + event.target.getAttribute (' value '));
  }
As the following illustration shows, we can see that the DOM properties change as we enter, but the HTML properties do not change.



Looking at an example of disabled:
<button disabled> Click </button>
The current button is not clickable because the disabled property appears.
<button disabled= "false" > click </button>
This button is not available when I set the disables (HTML property) to False. Adding or removing the disabled attribute disables or enables this button. But the value of the attribute is irrelevant, which is why we can't use the <button disabled= "false" > still be disabled </button> this notation to enable the button.
But we can use the DOM property to enable the button.
<button [disabled]= "false" > click </button>
Template bindings work through property and events, not attributes. In the angular world, the only function of attribute is to initialize the state of elements and instructions. When data binding is done, it is only in relation to the property and events of the elements and instructions, and the attribute is completely sidelined.
4 binding target (1) one-way from data source to view target a) an interpolation expression
{{Employee.Name}}}
B) Property bindings (DOM property bindings)
[target]= "expression"

<input type= "text" [value]= "name"/>
Some people prefer to use the optional form of the bind-prefix, called the canonical form:
<input type= "text" bind-value= "name"/>
property binding or an interpolation expression.
<p> is the <i>interpolated</i> image.</p>
<p>  is the <i>property bound</i> image.</p>
When the data type being rendered is a string, there is no technical justification for which form is better. We tend to be readable, so we tend to interpolate expressions. It is recommended that you establish code style rules and choose a form that allows you to follow the rules and make the task at hand more natural. However, when the data type is not a string, it must be bound using attributes.
c) Attribute binding
[attr.target]= "Expression"
You can set the value of an attribute directly by attribute binding.

Why angular also provides attribute binding.
Because when an element has no attributes to bind, it must be bound with attribute.
<tr><td colspan= ' {{1 + 1}} ' >One-Two</td></tr>


As the hint says, the,<td> element has no colspan attribute. However, interpolation expressions and property bindings can only set properties and cannot be set. We need attribute binding to create and bind to such attributes.

The syntax of attribute binding is similar to property binding. But the part of the square brackets is not the attribute name of the element, but the attr prefix, a point (.) and the name of the attribute. You can set the value of an attribute by an expression with a value of string.

This binds [Attr.colspan] to a computed value:
<TR><TD [attr.colspan]= "1 + 1" >One-Two</td></tr>
d) CSS class bindingsBy using CSS class bindings, you can add and remove CSS class names from the element's class attribute. The syntax of a CSS class binding binding is similar to a property binding. But the part of the square brackets is not the attribute name of the element, but the class prefix, a dot (.) and the name of the CSS class, where the last two parts are optional. Shaped like: [Class.class-name].

As an example:
. color-class {
  color:red
}
<div>
  <div class= "Color-class" >
    <p>test the CSS class bind</p>
  </div>
</div>
The text on the page is a red color at this time.

Then we use [class] to bind, and we can rewrite it as binding to the desired CSS class name, which is a or all or none of the substitution bindings.
<div>
  <div class= "Color-class" [class]= "ClassName" >
    <p>test the CSS class bind</p>
  </div>
</div>
In this case, set the class name on the [class] to the Div, and the class= "Color-class" will be replaced. It's a bit too violent, maybe I just want to manipulate a class. Then you can use the following method. You can bind to a specific class name. When a template expression evaluates to a true value, angular adds the class, and otherwise removes it.
<div [class.special]= "isspecial" >the class binding is special</div>
There is also a ngclass built-in instruction to wait until the instruction text is learned.
e) style bindingsWith style bindings, you can set an inline style.
[Style.style-property]
The syntax of a style binding is similar to a property binding. But the part of the square brackets is not the attribute name of the element, but the style prefix, a dot (.) and a CSS style property name.
<button [style.color]=] isspecial? ' Red ': ' Green ' >Red</button>
<button [style.background-color]=] cansave? ' Cyan ': ' Grey ' >Save</button>
Some style bindings have styles with units. Here, to set the font size units according to the condition with "em" and "%".
<button [style.font-size.em]=] isspecial? 3:1 ">Big</button>
<button [style.font-size.%]="!isspecial? 150:50 ">Small</button>
There is also a ngstyle built-in instruction to wait until the instruction text is learned.
(2) one-way from view target to data source a) event binding
(target) = "statement"
The name in parentheses-for example (click)-marks the target event. In the following example, the target is the click event for the button.
<button (click) = "OnSave ()" >Save</button>
Some people prefer the alternative form of on-prefixes, called canonical forms:
<button on-click= "OnSave ()" >on save</button>
b $event and event-handling statementsBindings pass information about this event, including data values, through an event object called $event.

The shape of the event object depends on the target event. If the target event is a native DOM element event, $event is the DOM event object.
<button (click) = "OnSave ($event)" >Save</button>
c) Eventemitter custom eventsThe angular eventemitter is used to trigger the custom event. The instruction creates a Eventemitter instance and exposes it as a property. The instruction calls Eventemitter.emit (payload) to trigger the event, which can be passed into anything as a message payload. The parent instruction listens to the event by binding to this property and accesses it through the $event object. Details can be viewed in output.
(3) bidirectional data bindingWe often need to display data properties and update the property when the user makes a change.
At the element level, it is necessary to set element attributes and to listen for element event changes.
Angular provides a special bidirectional data binding syntax for this: [(x)]. The [(x)] syntax combines the square brackets [x] of the property bindings with the parentheses (x) of the event bindings.
a) [()] = banana in the boxExample:
step.component.html
<div>
  <button (click) = "Dec ()" title= "smaller" >-</button>
  <button (click) = "Inc ()" title= "bigger" >+</button>
  <label [style.font-size.px]= "Size" > FontSize: {{size}}px</label>
</div>
Step.component.ts
Import {component, Eventemitter, Hostlistener, Input, Output} from ' @angular/core ';

@Component ({
  selector: ' App-step ',
  templateurl: './step.component.html ',
  styleurls: ['./ Step.component.css ']
})
Export class Stepcomponent {
  @Input ()
  size:number;

  @Output ()
  sizechange = new eventemitter<number> ();

  Dec () {this.resize (-1);}
  Inc () {this.resize (+ 1);}

  Resize (delta:number) {
    this.size = math.min (+, Math.max (8, + this.size + delta));
    This.sizeChange.emit (this.size);
  }

angular.component.html
<app-step [(size)]= "fontsizepx" ></app-step>
<div [ style.font-size.px]= "fontsizepx" >resizable text</div>
Angular.compoent.ts
Import {afterviewinit, Component, Elementref, OnInit, viewchild} from ' @angular/core ';
Import {Employee} from './angular.module ';

@Component ({
  selector: ' App-angular ',
  templateurl: './angular.component.html ',
  styleurls: ['./ Angular.component.css '],
})

Export class Angularcomponent {public
  fontsizepx:number =;


  Constructor () {
  }
}
The initial value of the stepcomponent:size is an input value from the property binding. Click on the @input in front of size to increase or decrease size within the minimum/maximum range limit. The Sizechange event is then triggered with the adjusted size.

The bidirectional binding syntax is actually a syntactic sugar for property bindings and event bindings. Angular the binding of stepcomponent into this way:
<app-step [size]= "fontsizepx" (sizechange) = "fontsizepx= $event" ></app-step>
b) NgmodelNeed formsmodule when using Ngmodel
Before using the Ngmodel instruction for two-way data binding, we must import the Formsmodule and add it to the Angular module's list of imports.
<input [(Ngmodel)]= "Currenthero.name" >
Looking back at the name binding, note that you can achieve the same effect by binding the Value property of the <input> element and the input event separately.
<input [value]= "Currenthero.name" (Input) = "Currenthero.name= $event. Target.value" >
That's cumbersome, who remembers which element attributes to set and which event to trigger when the user modifies. How do you extract the text from the input box and update the data properties? Who would want to check the data every time to make sure of it.

The ngmodel instruction hides those details through its own input attributes Ngmodel and output attributes Ngmodelchange.
<input [ngmodel]= "Currenthero.name" (ngmodelchange) = "Currenthero.name= $event" >
The Ngmodel input property sets the value of the element and listens for changes in the value of the element through the Ngmodelchange output property.

* Various elements have a number of unique processing details, so the Ngmodel directive only supports the implementation of CONTROLVALUEACCESSOR elements, which allow elements to fit this agreement. <input> input box is one of them. Angular provides a value accessor for all underlying HTML forms (value accessor), and the table single chapter shows how to bind them.

Reference: Https://www.angular.cn/guide/template-syntax

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.