AI Hints
Home›Angular Tutorial›Property Binding, Event Binding and ng generate component
Angular · Lesson 22 of 120

Property Binding

[property]="value".

⏱ 2 min read▶ Video at 26:40🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Interpolation puts values into text. But sometimes we want to set a property of an element. Like the picture an image shows, or whether a button is disabled.

  • Not just text
  • Element properties
  • src, disabled, style

Square brackets

Square brackets around a property name bind it to a value from the class. The right side is TypeScript, not text. When the value changes, the property updates. And style dot colour sets a single style, the same way.

keyvalue
[src]="cover"the image to show
[disabled]="stock === 0"on or off
[style.color]="..."one style
Right sidea TypeScript expression

Binding properties

The image source is bound to cover, a picture from the class. The heading's title, the text you see when hovering, is built from the author. The button is disabled, when the stock is zero. And the stock colour turns red, when it's sold out. Run it. Dune is out of stock, so the button is greyed out, and the stock is red.

app.tstypescript
import { Component } from '@angular/core';
import { COVER } from './cover';

@Component({
  selector: 'app-root',
  template: `
    <img [src]="cover" [alt]="title" width="90">
    <h2 [title]="'Written by ' + author">{{ title }}</h2>
    <button [disabled]="stock === 0">Add to basket</button>
    <p [style.color]="stock === 0 ? 'crimson' : 'green'">Stock: {{ stock }}</p>
  `,
})
export class App {
  cover = COVER;
  title = 'Dune';
  author = 'Frank Herbert';
  stock = 0;
}
Also uses cover.ts
export const COVER = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='170'%3E%3Crect width='120' height='170' rx='8' fill='%23c3002f'/%3E%3Ctext x='60' y='95' font-size='26' font-family='Helvetica' fill='white' text-anchor='middle'%3EDune%3C/text%3E%3C/svg%3E";

Quotes matter

With square brackets, the right side is code, so a name means a property of the class. Without them, it's just fixed text. So square brackets src equals cover, shows the cover. But src equals cover, without brackets, looks for a file called cover.

[src]="cover"

  • codethe class's covervalue can change

src="cover"

  • plain texta file named covernever changes

Summary

Square brackets bind an element property to a value from the class, and update it when the value changes. Next, event binding.

Key takeaways
  • [src]
  • [disabled]
  • [style.color]
Next up: Event Binding — (event)="handler()"