Property Binding and Event Binding
11 min read
Binding Data to DOM Properties
Property binding lets you set a DOM element's property from a TypeScript expression. Wrap the target property in square brackets [property] and assign an expression. This is a one-way data flow from component to template.
html
<img [src]="imageUrl" [alt]="imageAlt" />
<button [disabled]="isLoading">Submit</button>
<input [value]="currentValue" />
<div [class.active]="isActive">Tab</div>
<p [style.color]="brandColor">Styled text</p>Event Binding
Event binding lets you listen to DOM events and run TypeScript methods. Wrap the event name in parentheses (event) and assign a method call or statement. The special $event variable gives you access to the native event object.
ts
import { Component } from '@angular/core';
@Component({
selector: 'app-counter',
standalone: true,
template: `
<p>Count: {{ count }}</p>
<button (click)="increment()">+</button>
<button (click)="decrement()">-</button>
<button (click)="reset()">Reset</button>
<input (input)="onInput($event)" />
<p>Typed: {{ typed }}</p>
`
})
export class CounterComponent {
count = 0;
typed = '';
increment() { this.count++; }
decrement() { this.count--; }
reset() { this.count = 0; }
onInput(event: Event) {
this.typed = (event.target as HTMLInputElement).value;
}
}Remember the mnemonic: [brackets] for in to the component (property binding), (parens) for out from the component (event binding), and [(banana-in-box)] for two-way binding.
Ready to test yourself?
Practice Angular— quiz & coding exercises