FrontEndTech
  • Introduction
  • ReactJS
    • Ecosystem
    • Refactor Using Functional Decomposition and Reducer Composition
  • AngularJS
    • installation
    • File structure
    • CLI
      • ng g
    • Fundamentals
      • Component
        • Lifecycle
        • Template
      • Decorations
      • Service
      • Pipe
      • Directives
        • NgClass
        • NgStyle
        • NgModel
        • Customized Attribute Directives
        • NgIf
        • NgFor
        • NgSwitch
        • NgForm
        • Customized Structural Directives
      • Module
        • Routing
    • Bindings
      • Property Binding
      • Event Binding
      • Data Binding
      • Attribute Binding
      • Class Binding
      • Style Binding
    • Forms
      • Reactive Form
      • Reactive vs Template
    • build
Powered by GitBook
On this page
  • Interpolation
  • Directives
  • Template Expression
  • Guidelines
  • Template Statement
  • Difference from template expression
  • Same with template expression
  • Template Input Variable
  • Template Input Variables' Precedence
  • Template reference variables (#var)
  • How a reference variable gets its value

Was this helpful?

  1. AngularJS
  2. Fundamentals
  3. Component

Template

PreviousLifecycleNextDecorations

Last updated 5 years ago

Was this helpful?

Interpolation

the text between the braces is a template expression that Angular first evaluates and then converts to a string. Finally, it assigns this composite interpolated result to an element or directive property.

<p>My current hero is {{currentHero.name}}</p>
<img src="{{heroImageUrl}}" style="height:30px">

Directives

Further info see

[R]

Template Expression

Many JavaScript expressions are legal template expressions, but not all. JavaScript expressions that have or promote side effects are prohibited, including:

  • assignments (=, +=, -=, ...)

  • new chaining expressions with ; or ,

  • increment and decrement operators (++ and --)

differences from JavaScript syntax include:

  • bitwise operators | and &

  • new template expression operators

    • pipe operator |

    • safe navigation operator ?.

    • non-null assertion operator!.

  • Pipe operator

<div>Title through uppercase pipe: {{title | uppercase}}</div>
  • Safe navigation operator

The current hero's name is {{currentHero?.name}}

You can also write as following, but is cumbersome especially if the property path is long. e.g. a.b.c.d

It works perfectly with long property paths such as a?.b?.c?.d

<div *ngIf="nullHero">The null hero's name is {{nullHero.name}}</div>
The null hero's name is {{nullHero && nullHero.name}}
  • Non-null assertion operator

<div *ngIf="hero">
  The hero's name is {{hero!.name}}
</div>

When the Angular compiler turns your template into TypeScript code, it prevents TypeScript from reporting that hero.name might be null or undefined. Unlike the safe navigation operator, the non-null assertion operator does not guard against null or undefined. Rather it tells the TypeScript type checker to suspend strict null checks for a specific property expression.You'll need this template operator when you turn on strict null checks. It's optional otherwise.

Template expressions cannot refer to anything in the global namespace (except undefined). They can't refer to window or document. They can't call console.log or Math.max. They are restricted to referencing members of the expression context.

Guidelines

  • No visible side effects

    • A template expression should not change any application state other than the value of the target property.

  • Quick execution

    • Expressions should finish quickly or the user experience may drag

  • Simplicity

    • A property name or method call should be the norm. An occasional Boolean negation (!) is OK.

  • Idempotence

    • an idempotent expression always returns exactly the same thing until one of its dependent values changes.

Template Statement

A template statement responds to an event raised by a binding target such as an element, component, or directive.

<button (click)="deleteHero()">Delete hero</button> <!--(event)="statement"-->

Difference from template expression

  1. supports both basic assignment (=) and chaining expressions (with ; or ,).

  2. certain JavaScript syntax is not allowed (allowed in template expression)

    1. the bitwise operators | and &

Same with template expression

  1. The statement context is typically the component instance. The statement context may also refer to properties of the template's own context.

  2. Template statements cannot refer to anything in the global namespace. They can't refer towindowordocument. They can't callconsole.logorMath.max.

  3. Support javascript syntax

    1. new

    2. increment and decrement operators, ++ and --

    3. operator assignment, such as += and -=

<button (click)="deleteHero()">Delete hero</button>            <!-- component instance -->
<button (click)="onSave($event)">Save</button>                 <!-- template $event object -->
<button *ngFor="let hero of heroes" (click)="deleteHero(hero)">{{hero.name}}</button> 
                                                                <!-- template input variable -->

<form #heroForm (ngSubmit)="onSubmit(heroForm)"> ... </form>   <!-- template reference variable -->

Template Input Variable

You declare a template input variable using the let keyword (let hero). The variable's scope is limited to a single instance of the repeated template. You can use the same variable name again in the definition of other structural directives.

Template Input Variables' Precedence

If you reference a name that belongs to more than one of these namespaces, the template input variable name takes precedence, followed by a name in the directive's context, and, lastly, the component's member names.

<input type="text" name="Kiwi" #hero>                    <!-- 2nd priority -->
<div *ngFor="let hero of heroes">{{hero.name}}</div>     <!-- 1st priority -->
After looping, hero name is {{hero.name}}
export class AppComponent {
  hero = {
    name: 'Cathy'
  };                                                      /* 3rd priority */

  heroes = [{ name: 'Charles' }, { name: 'Raymond' }, { name: 'Lisa' }];
}

Result

Charles
Raymond
Lisa
After looping, hero name is Kiwi

Template reference variables (#var)

You declare a template reference variable by prefixing the variable name with # (#var).

Could be a reference to

  • a DOM element within a template

  • an Angular component

  • directive

  • a web component

<input #phone placeholder="phone number"> // or
<input ref-phone placeholder="phone number"> 

<button (click)="callPhone(phone.value)">Call</button>

The scope of a reference variable is the entire template. Do not define the same variable name more than once in the same template.

How a reference variable gets its value

In most cases, Angular sets the reference variable's value to the element on which it was declared.

The following is a simplified version of the form example in the Forms guide:

<form (ngSubmit)="onSubmit(heroForm)" #heroForm="ngForm">
  <div class="form-group">
    <label for="name">Name
      <input class="form-control" name="name" required [(ngModel)]="hero.name">
    </label>
  </div>
  <button type="submit" [disabled]="!heroForm.form.valid">Submit</button>
</form>
<div [hidden]="!heroForm.form.valid">
  {{submitMessage}}
</div>

The native <form> element doesn't have a form property. But the NgForm directive does.

The heroForm is actually a reference to an Angular NgForm directive with the ability to track the value and validity of every control in the form.

The backtick ````` allows you to compose a string over several lines, which makes the HTML more readable.

`<h1>{{title}}</h1>
<h2>My favorite hero is: {{myHero}}</h2>`

[R]

[R]

the

Template context names precedence rule :

[R]

Before you imported the, #heroForm would be the . After Angular take it over, theheroFormis actually a reference to an Angular directive with the ability to track the value and validity of every control in the form.

Directives
https://angular.io/guide/displaying-data
https://angular.io/guide/template-syntax#expression-operators
Pipe
template expression operators
reference
https://angular.io/guide/structural-directives#template-input-variable
FormsModule
HTMLFormElement
NgForm