FresherTechnicalAngular
Explain interpolation, property binding and event binding in Angular templates
Try answering first
Model answer
These three bindings connect the component class to the template.
- Interpolation
{{ expression }}renders a value as text. - Property binding
[property]="expression"sets a DOM property or a component input. - Event binding
(event)="handler()"listens to a DOM event or a component output.
<h1>{{ title }}</h1>
<img [src]="imageUrl" [alt]="title" />
<button (click)="save($event)" [disabled]="saving">Save</button>
title = 'Profile'
imageUrl = '/avatar.png'
saving = false
save(event: MouseEvent) {
this.saving = true
}
Notes:
$eventis the event object, or the emitted value of an output.- Bindings to properties differ from HTML attributes. For attributes without a property, such as ARIA, use
[attr.aria-label]="label". - Combining a property and an event gives two-way binding, written
[(ngModel)]. - Expressions must be simple and free of side effects, because Angular evaluates them often.
Use brackets to push data in and parentheses to listen for events.
Key points
- Interpolation renders text
- Brackets bind properties and inputs
- Parentheses bind events and outputs
- Use attr. for attributes without a property
Likely follow-ups
- What is the difference between a property and an attribute?
Common mistakes
- Writing disabled="saving" and expecting it to bind
- Putting side effects or heavy work in template expressions