Template Syntax

📚 Template Syntax Overview

  • Interpolation: {{ expression }} - Display data
  • Property Binding: [property]="expression" - Bind to element property
  • Event Binding: (event)="handler()" - Listen to events
  • Two-way Binding: [(ngModel)]="property" - Combine property + event
  • Attribute Binding: [attr.name]="value" - Bind to attributes
  • Class Binding: [class.active]="isActive" - Toggle classes
  • Style Binding: [style.color]="color" - Set inline styles
  • Template Reference: #variableName - Reference elements

🎯 Interview Questions

  • Q1: What is the difference between property binding and attribute binding?
  • A: Property binding sets DOM property ([value]), attribute binding sets HTML attribute ([attr.value]). Properties are dynamic, attributes are static initial values.
  • Q2: What is two-way binding and how does it work?
  • A: [(ngModel)] is shorthand for [ngModel]="value" (ngModelChange)="value=$event". Combines property + event binding.
  • Q3: What are template reference variables?
  • A: #ref creates reference to DOM element or component, accessible within template.

🔧 Interpolation {{ }}

String: Hello, Angular!

Expression: 15

Method call: This is from a method

Signal: 42

🔧 Property Binding [property]

Angular Logo

🔧 Event Binding (event)

Clicked: 0 times

Input value:

🔧 Class & Style Binding

Dynamic class binding

Dynamic style binding

16px

🔧 Template Reference #ref

💻 Template Syntax Examples


// Interpolation
<p>{{ greeting }}</p>
<p>{{ 5 + 10 }}</p>
<p>{{ count() }}</p>  <!-- Signal -->

// Property Binding
<img [src]="imageUrl" [alt]="imageAlt" />
<button [disabled]="isDisabled()">Click</button>

// Event Binding
<button (click)="handleClick()">Click</button>
<input (input)="onInput($event)" />
<input (keyup.enter)="onEnter()" />

// Class Binding (prefer over ngClass)
<p [class.active]="isActive()">Text</p>
<p [class]="{ 'bold': isBold(), 'error': hasError() }">Text</p>

// Style Binding (prefer over ngStyle)
<p [style.color]="textColor()">Text</p>
<p [style.font-size.px]="fontSize()">Text</p>

// Attribute Binding
<button [attr.aria-label]="label">Icon</button>
<td [attr.colspan]="columns">Cell</td>

// Template Reference Variable
<input #nameInput type="text" />
<button (click)="greet(nameInput.value)">Greet</button>

// Two-way Binding (requires FormsModule)
<input [(ngModel)]="name" />