Data Binding
Data Binding
Section titled βData BindingβWhat it means
Section titled βWhat it meansβ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).
Examples
Section titled βExamplesβ@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++; }}Common mistake
Section titled βCommon mistakeβ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">Quick practice
Section titled βQuick practiceβ-
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. -
What does
[(ngModel)]="name"combine?Answer
Property binding and event binding together β it both displaysnamein the input and updatesnamewhen the user types, in one directive (requires importingFormsModule). -
What happens if you write
src="avatarUrl"without square brackets?Answer
Angular 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.