Sub topic 1
How Angular Templates Connect to Component State
An Angular component has two halves: a TypeScript class that holds state, and a template that renders it. Bindings connect the two. This chapter covers one-way bindings, where data flows from the class to the DOM.
Prerequisites
This chapter assumes you know HTML and the DOM, TypeScript classes, and how to generate and serve a component with the Angular CLI.
Template Expressions
A template expression is a small piece of JavaScript-like code that Angular evaluates against the component instance. When you write name in a binding, you are reading the class field this.name. Expressions should be fast and free of side effects, because Angular re-evaluates them on every change detection pass.
Interpolation and Property Binding
Interpolation ({{ }}) converts an expression to a string and inserts it as text. Property binding ([prop]="expr") sets a DOM property to the expression's value, and the value keeps its type. For example, [disabled] receives a real boolean.
import { Component } from '@angular/core';
@Component({
selector: 'app-profile',
template: `
<h2>{{ name }}</h2>
<img [src]="avatarUrl" [alt]="name">
<button [disabled]="!canEdit">Edit</button>
`,
})
export class ProfileComponent {
name = 'Ada';
avatarUrl = '/assets/ada.png';
canEdit = false;
}Attribute, Class and Style Bindings
HTML attributes set the initial state of an element. DOM properties hold its current state. Property binding targets properties, so it fails when an attribute has no matching property. colspan is one example. Use attr. for those cases. Use class. to toggle a single CSS class and style. to set a single style, with an optional unit suffix.
import { Component } from '@angular/core';
@Component({
selector: 'app-table-cell',
template: `
<table><tr><td [attr.colspan]="span">Total</td></tr></table>
<div [class.active]="isActive" [style.width.px]="width">Panel</div>
`,
})
export class TableCellComponent {
span = 2;
isActive = true;
width = 240;
}| Binding | Targets | Example |
|---|---|---|
| `[prop]` | DOM property | `[src]="url"` |
| `[attr.x]` | HTML attribute | `[attr.colspan]="span"` |
| `[class.x]` | One CSS class | `[class.active]="isActive"` |
| `[style.x.unit]` | One style | `[style.width.px]="width"` |
Exercise
Why does <td [colspan]="span"> throw a template error, and how do you fix it?
Show answer
Binding to the colspan property fails because the DOM property is named colSpan, so no colspan property exists. Bind to the attribute with [attr.colspan]="span".
Exercise
The binding is [disabled]="canEdit" and canEdit is false. Is the button disabled?
Show answer
No. Property binding passes the boolean false to the disabled property, so the button is enabled.