Templates
Templates
Section titled βTemplatesβWhat it means
Section titled βWhat it meansβAn Angular componentβs template is HTML augmented with Angular-specific syntax β interpolation ({{ }}), bindings ([], ()), and structural control flow (@if, @for) β that connects the markup to the component class. Templates can be defined inline (template: β¦β in the decorator) or in a separate .html file (templateUrl: './component.html').
Examples
Section titled βExamplesβ@Component({ selector: 'app-user-card', template: ` <div class="card"> <h2>{{ user.name }}</h2> @if (user.isPremium) { <span class="badge">Premium</span> } <ul> @for (role of user.roles; track role) { <li>{{ role }}</li> } </ul> <button (click)="onEdit()">Edit</button> </div> `,})export class UserCardComponent { @Input() user!: User; @Output() edit = new EventEmitter<void>();
onEdit() { this.edit.emit(); }}
// Template reference variables -- grab a reference to a DOM element or directive// <input #emailInput> ... {{ emailInput.value }}Common mistake
Section titled βCommon mistakeβPutting complex logic directly in the template instead of a computed property or method on the component class β Angular templates support expressions, but theyβre not meant to hold branching business logic, and complex inline expressions are hard to read, test, and reuse.
<!-- Hard to read, hard to test, re-evaluated on every change detection cycle --><p>{{ (user.age >= 18 && user.hasId) ? 'Eligible' : (user.age >= 16 ? 'Minor with restrictions' : 'Not eligible') }}</p>// Better: move the logic to the component (or use a computed signal)get eligibilityStatus(): string { if (this.user.age >= 18 && this.user.hasId) return 'Eligible'; if (this.user.age >= 16) return 'Minor with restrictions'; return 'Not eligible';}<p>{{ eligibilityStatus }}</p>Quick practice
Section titled βQuick practiceβ-
Whatβs the difference between
templateandtemplateUrlin a@Component()decorator?Answer
templatedefines the HTML inline in the TypeScript file;templateUrlpoints to a separate.htmlfile β functionally equivalent, chosen based on template size/preference. -
Why should complex conditional logic generally live in the component class rather than directly in a template expression?
Answer
Component-class logic (methods, getters, computed signals) is easier to read, unit test, and reuse than a long inline template expression, which also gets re-evaluated on every change detection cycle. -
What does
#emailInput(a template reference variable) let you do?Answer
Access the referenced DOM element (or directive/component instance) directly elsewhere in the same template β e.g. readingemailInput.valuefrom an input field without two-way binding.