Basics
Templates & Interpolation
{{ }} Syntax
💡 Interpolation ek fill-in-the-blank form hai — {{ }} ke andar variable naam likh do, Angular automatically usse ACTUAL VALUE se replace kar deta hai, aur jab value badalti hai, template automatically UPDATE hota hai (live).
Template Angular ka HTML hai, JISME special Angular syntax (interpolation, directives, bindings) use ho sakta hai. Interpolation {{ expression }} — kisi bhi JavaScript-jaisi expression ka result string mein display karta hai. Automatically UPDATE hota hai jab underlying data change hoti hai ("data binding").
// Component:
export class ProfileComponent {
name = 'Riya';
age = 22;
getGreeting() {
return 'Hello!';
}
}
// Template:
// <p>Name: {{ name }}</p>
// <p>Age: {{ age }}</p>
// <p>Next year: {{ age + 1 }}</p> expressions bhi chal sakte hain
// <p>{{ getGreeting() }}</p> method calls bhi
// <p>{{ name.toUpperCase() }}</p>✏️
Interpolation ek fill-in-the-blank form hai — {{ }} ke andar variable naam likh do, Angular automatically usse ACTUAL VALUE se replace kar deta hai, aur jab value badalti hai, template automatically UPDATE hota hai (live).
1 / 2
⚡ Quick Recap
- {{ expression }} = interpolation, dynamic value display karta hai
- Automatically updates jab underlying data badalti hai
- Simple expressions hi allowed — complex logic class mein rakho
On this page (2 subtopics)
Template expressions JavaScript jaisi lagti hain, lekin SAB JavaScript features support nahi karti — assignment operators (=, +=), new, increment (++/--), bitwise operators allowed NAHI hain security aur predictability ke liye.
// GALAT (template expressions mein allowed nahi):
// {{ count = count + 1 }} // assignment — ERROR
// {{ new Date() }} // new keyword — ERROR
// SAHI:
// {{ count + 1 }} // simple expression — OK
// {{ getCurrentDate() }} // method call jo Date return kare — OKCommon Mistake: Template expressions "side-effect-free" honi chahiye — sirf VALUE read/calculate karo, kuch CHANGE mat karo. Agar state change karni hai, event binding (click handler) use karo, interpolation nahi.
Template mein ?. (safe navigation/Elvis operator) null/undefined properties access karte waqt crash se bachata hai — JavaScript ke optional chaining jaisa hi concept.
// Agar user null ho sakta hai:
// <p>{{ user?.name }}</p>
// Agar user null hai, error NAHI aayega, bas khaali dikhega
// Bina ?. ke (RISKY):
// <p>{{ user.name }}</p> — user null ho to ERROR crash karega template koTip: API se data load hone se PEHLE (jab tak async data nahi aaya), properties usually undefined/null hoti hain — ?. is common scenario ko safely handle karta hai bina extra *ngIf checks ke.