Skip to content

Templates

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').

@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 }}

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>
  1. What’s the difference between template and templateUrl in a @Component() decorator?

    Answertemplate defines the HTML inline in the TypeScript file; templateUrl points to a separate .html file β€” functionally equivalent, chosen based on template size/preference.
  2. Why should complex conditional logic generally live in the component class rather than directly in a template expression?

    AnswerComponent-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.
  3. What does #emailInput (a template reference variable) let you do?

    AnswerAccess the referenced DOM element (or directive/component instance) directly elsewhere in the same template β€” e.g. reading emailInput.value from an input field without two-way binding.