Data Binding and Interpolation
Data Binding and Interpolation
Angular keeps templates and component classes in sync through data binding. You bind values from the class into the view and respond to events coming back up.
Interpolation
Double curly braces display a class value:
<p>Total: {{ total }}</p>
You can call methods and use expressions inside braces:
<p>Full: {{ firstName + ' ' + lastName }}</p>
Property binding
Square brackets bind a target property to a class expression:
<img [src]="user.photo" [alt]="user.name" />
Property binding one-way flows from class to view. When the class value changes, Angular updates the attribute.
Event binding
Parentheses listen for events and run methods:
<button (click)="increment()">Add one</button>
<input (input)="onTyping($event)" />
$event carries the event data, such as the value typed into an input.
Two-way binding
With ngModel you combine property and event binding so typing updates a class field and class updates refresh the input:
<input [(ngModel)]="search" />
Import FormsModule in your component setup, and the input and the search field stay in sync. The banana-in-a-box syntax, [()], marks two-way binding.
Choosing the right binding
Use interpolation or property binding for display, event binding for actions, and ngModel when a form field needs to update state both ways. Prefer one-way flow when possible because it is easier to reason about.
Key Points
- Interpolation uses double curly braces for display.
- [property] binding flows class to view.
- (event) binding runs methods on user actions.
- $event exposes the event payload.
- [(ngModel)] gives two-way form binding.