Skip to content

Data Binding

Data binding connects a component’s TypeScript class to its HTML template. Angular has four kinds: interpolation ({{ value }}, display data), property binding ([property]="value", set an element property from the class), event binding ((event)="handler()", run class code on a DOM event), and two-way binding ([(ngModel)]="value", combines property + event for forms).

@Component({
selector: 'app-profile',
template: `
<h1>{{ name }}</h1> <!-- interpolation -->
<img [src]="avatarUrl" [alt]="name"> <!-- property binding -->
<button (click)="incrementScore()">+1</button> <!-- event binding -->
<input [(ngModel)]="name"> <!-- two-way binding -->
`,
})
export class ProfileComponent {
name = 'Alice';
avatarUrl = '/images/alice.png';
score = 0;
incrementScore() {
this.score++;
}
}

Forgetting the brackets on property binding and writing src="avatarUrl" instead of [src]="avatarUrl" β€” without brackets, Angular treats the right-hand side as a literal string, not an expression to evaluate against the component class.

<!-- Wrong: sets the actual attribute to the literal text "avatarUrl" -->
<img src="avatarUrl" alt="Profile">
<!-- Correct: evaluates `avatarUrl` as a class property and binds its value -->
<img [src]="avatarUrl" alt="Profile">
  1. What’s the difference between {{ name }} and [value]="name"?

    Answer{{ name }} is interpolation, used inside text content; [value]="name" is property binding, used to set an element or component property directly β€” interpolation is actually shorthand for a special case of property binding on text nodes.
  2. What does [(ngModel)]="name" combine?

    AnswerProperty binding and event binding together β€” it both displays name in the input and updates name when the user types, in one directive (requires importing FormsModule).
  3. What happens if you write src="avatarUrl" without square brackets?

    AnswerAngular sets the attribute to the literal string "avatarUrl" instead of evaluating it as a class property β€” the brackets are what tell Angular to treat the right side as an expression.