Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Property and event binding

Interpolation outputs text, but elements also need other data: an image address, a button state, a class. Property binding — square brackets — handles that. The opposite direction, from the user to the class, is event binding in parentheses.

Property binding

The property name goes in square brackets, an expression from the class on the right:

// src/app/todo-list/todo-list.ts
import { Component } from '@angular/core';
 
@Component({
  selector: 'app-todo-list',
  templateUrl: './todo-list.html',
})
export class TodoList {
  newTitle = '';
}
<!-- src/app/todo-list/todo-list.html -->
<input placeholder="New task" />
<button [disabled]="newTitle === ''">Add</button>

The button is disabled while newTitle is empty. Without brackets the attribute disabled="..." would get a string, and the button would always be disabled.

Classes and styles

A single class and a single CSS property can be bound too:

<!-- src/app/todo-list/todo-list.html -->
<li [class.done]="true">Buy bread</li>
<p [style.color]="newTitle ? 'black' : 'gray'">Hint</p>

The done class is added when the expression is true and removed when it is false.

Event binding

The event name goes in parentheses, a method call on the right:

// src/app/todo-list/todo-list.ts
export class TodoList {
  newTitle = '';
  tasks: string[] = [];
 
  add() {
    this.tasks.push(this.newTitle);
    this.newTitle = '';
  }
}
<!-- src/app/todo-list/todo-list.html -->
<button (click)="add()">Add</button>
<p>Total tasks: {{ tasks.length }}</p>

After every click the "Total tasks" counter goes up by one.

The event object

The $event variable holds the browser's event object. You can take the field's text from it, for example:

<!-- src/app/todo-list/todo-list.html -->
<input
  placeholder="New task"
  [value]="newTitle"
  (input)="newTitle = $any($event.target).value"
/>
<button [disabled]="newTitle === ''" (click)="add()">Add</button>

Now the field and the class are connected: typing writes the text into newTitle, the button becomes enabled, and after a click the field is cleared. Assignment is allowed in an event handler. The $any function turns off the type check, because TypeScript does not know that target is an input field.

Template variable

It is simpler to get an element through a template variable — a name with a hash sign:

<!-- src/app/todo-list/todo-list.html -->
<input #field [value]="newTitle" (keyup.enter)="newTitle = field.value; add()" />

#field refers to the input element itself. The keyup.enter event fires only on the Enter key.

Common mistake

You cannot mix interpolation and square brackets: [disabled]="{{ isEmpty }}" causes a build error. The square brackets already contain an expression — write [disabled]="isEmpty".

Thanks for reading!

Donate to the site — we work hard for you.