Template Syntax

AngularDart templates look like HTML, but with additional syntax that lets AngularDart modify the DOM at runtime.

Interpolation

Use double curly braces {{ }} to display component property values:

<p>{{ greeting }}, {{ user.name }}!</p>

Interpolation expressions can use pipes to transform values:

<p>Today is {{ today | date }}</p>
<p>Price: {{ price | currency:'EUR' }}</p>

Property Binding

Square brackets [] bind an element property to a template expression:

<img [src]="user.imageUrl">
<button [disabled]="isUnchanged">Save</button>
<div [class.special]="isSpecial">Special</div>
<div [style.color]="isSpecial ? 'red' : 'green'">Styled</div>

Attribute Binding

Use [attr.] prefix to bind to HTML attributes:

<button [attr.aria-label]="action">Action</button>

Event Binding

Parentheses () bind an element event to a component method:

<button (click)="onSave()">Save</button>
<input (input)="onInput($event)">
<form (ngSubmit)="onSubmit()">

The $event Object

The $event object contains data about the event:

<input (input)="name = $event.target.value">
<button (click)="onClick($event)">Click me</button>

Template Reference Variables

Use # to declare a reference to a DOM element:

<input #nameInput>
<button (click)="greet(nameInput.value)">Greet</button>

Two-Way Binding

Use [( )] (banana-in-a-box) for two-way data binding:

<input [(ngModel)]="user.name">

This is equivalent to:

<input [ngModel]="user.name" (ngModelChange)="user.name = $event">

Built-in Directives

ngIf

Conditionally include or exclude elements:

<div *ngIf="user">Hello, {{ user.name }}</div>
<div *ngIf="isLoading; else noData">Loading...</div>
<ng-template #noData>No data available</ng-template>

ngFor

Repeat elements for each item in a list:

<li *ngFor="let item of items; let i = index">
  {{ i + 1 }}. {{ item.name }}
</li>

Additional context variables: first, last, even, odd, count.

ngSwitch

Conditionally swap elements:

<div [ngSwitch]="status">
  <span *ngSwitchCase="'active'">Active</span>
  <span *ngSwitchCase="'inactive'">Inactive</span>
  <span *ngSwitchDefault>Unknown</span>
</div>

ngClass and ngStyle

Set multiple classes or styles dynamically:

<div [ngClass]="{'special': isSpecial, 'active': isActive}">
  Content
</div>
<div [ngStyle]="{'font-weight': isBold ? 'bold' : 'normal', 'color': color}">
  Styled text
</div>

Pipes

Transform displayed values with pipes:

<p>{{ birthday | date }}</p>
<p>{{ price | currency:'EUR' }}</p>
<p>{{ name | uppercase }}</p>
<p>{{ data | json }}</p>
<p>{{ bigNumber | number:'1.2-2' }}</p>

Chain pipes:

<p>{{ birthday | date:'fullDate' | uppercase }}</p>

Safe Navigation Operator

Use ?. to guard against null and undefined values:

<p>The user's name is: {{ user?.name }}</p>

Non-null Assertion

Use ! to assert a value is non-null:

<p>{{ user!.name }}</p>