Skip to content

Templates

A template in Angular is a chunk of HTML. It is a special syntax to call TypeScript-specific things from Angular inside template.

Interpolation

Interpolation allowes the developer to incorporate dynamic string values into HTML templates. The most common use-case for interpolation is to dynamically change what appears in an application view, such as displaying a custom greeting that includes the user's name. Example:

Displaying Values with Interpolation

Interpolation refers to embedding expressions into marked up text. By default, interpolation uses the double curly braces {{ and }} as delimiters.

// inside component class: (_`src/app/app.component.ts`_)
loggedinUser = "Jon";
<!-- inside template: (_`src/app/app.component.html`_) -->
<h3>Good Morning, {{ loggedinUser }}</h3>

Resolving Expression with Interpolation

Text interpolation can also be used to resolve certain expressions. For example, we can do mathematical operations, string concatenation, using ternary operators or even calling a method etc. Example:

<!-- inside template: (_`src/app/app.component.html`_) -->
<h3>10 + 2 = {{ 10 + 2 }}</h3>
<h3>{{ true ? "d-day" : "not today" }}</h3>
<h3>time is {{ dt.toLocaleTimeString() }}</h3>
<h3>parse float {{ winref.parseFloat("1212.222323") }}</h3>

since all variables in an Angular template is called on the context of the conponent instance, any window methods such as window.parseFloat will not work. To get that working, we have to get a reference to the window objest and store it inside component class as a public property, and then use it inside the template.

Point to be noted, Angular will always type-cast whatever is inside double curly braces to string.

Illegal Operators in Expression

Following are the operators which Angular does not support in a template expression. These operators creates side-effects.

  • Assignments (=, +=, -=, ...)
  • Operators such as new, typeof, or instanceof
  • Chaining expressions with ; or ,
  • The increment and decrement operators ++ and --
  • No support for the bitwise operators such as | and &
  • New template expression operators, such as |, ?. and !
Expression Best Practices

When using template expressions, follow these best practices:

  • use short expressions
  • quick execution
  • no visible side effects

Template Statements

Template statements are methods or properties that you can use in HTML Template to respond to user events. With template statements, an Angular application can engage users through actions such as displaying dynamic content or submitting forms. Example:

<button (click)="deleteHero()">Delete hero</button>

Syntax

Template statements are similar to Template Expressions. Just like template expressions, template statements does not allow certain types of operators.

  • new
  • increment and decrement, ++ and --
  • operator assignment such as += or -=
  • the bitwise operators such as | and &
  • the Pipe Operator

Statement Best Practices

  • conciseness: keep template statements minimal by using method calls or basic property assignments.
  • work within the context: template statement refers to either the template itself or the component class instance. so, calling anything in the global namespace won't work

Pipes

Pipes in Angular are similar to pipes in Shell Scripting. A pipe takes an input value and return a transformed value. Pipes are useful because each pipe needs to be declared once and can be used throughout the application.

Built-in Angular pipes:

  • DatePipe: formats date according to local rules
  • UpperCasePipe: transforms text to uppercase
  • LowerCasePipe: transforms text to lowercase
  • CurrencyPipe: transforms a number to a currency string, formatted according to locale rules.
  • DecimalPipe: transforms a number into a string with a decimal point, formatted according to locale rules.
  • PercentPipe: transforms a number to a percentage string, formatted according to locale rules.

Using Pipes

the pipe operator (|) is used to 'pipe' an input value. example:

<p>The hero's birthday is {{ birthday | date }}</p>

Pipe can also accept optional arguments separated by colons (:). example:

<p>{{ birthday | date:'EUR':'Euros' }}</p>

Pipes can also be chained.

Writing Custom Pipes

Angular allows user to write custom pipe using @Pipe() decorator. Conventions for writing a pipe name are:

  1. pipe Class Name should be in PascalCase
  2. pipe name should be in camelCase
  3. no hyphens

Generate a pipe using ng generate pipe PIPE_NAME. Then, fill it up with the pipe logic.

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({ name: "exponentialStrength" })
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, exponent = 1) {
    return Math.pow(value, exponent);
  }
}

Property Binding

Property binding in Angular allows user to set values for properties of HTML elements or directives. Property Binding can be helpful for doing things like toggling button functionality, set paths programatically etc.

Interpolation and Property Binding only works with properties, and not attributes.

<img [src]="itemImageUrl" />
<!-- the `itemImageUrl` must be defined inside the component class -->

the square brackets ([]) cause Angular to evaluate the right hand side as an expression.

Pros of Property Binding

  • prevents XXS attacks by not letting malicious content pass
  • bind values between components

Class, Attribute and Style Binding

Class, Attribute and Style Bindings are similar to Property Binding. However, there are certain differences. In attribute binding, an attribute name must be prefixed with attr.. For example, to bind to aria-label attribute: <img src="path/to/img.png" [attr.aria-label]="expression" />. When the expression resolves to null or undefined, Angular removes the attribute altogather.

Binding Class

A class can be bound to an element in two ways: either a single class, or multiple classes at once. for example:

<!-- multiple classes bound at once -->
<span [class]="expression">multiple classes</span>

<!-- single class -->
<span [class.new]="isNew">a single class</span>

in above example, Angular will add new class to span element when the isNew expression resolves to true.

Binding Styles

Style binding works similar to class binding. For a single style property, for example background-color, it should be written as <p [style.background-color]="expression">lorem ipsum</p>. To bind multiple style properties, just use [style]="expression". expression in multi-property binding must return an object.

Styles can also be bound along with the units. For example: [style.width.px]="width".

Style Properties can be written as dash-case or camelCase

For style precedence, please check this