Angular Web Framework Components & Templates 3 — Questions and Answers
Question 1: Which Angular template syntax creates a local template reference variable for a DOM element?
- @ref
- *ref
- #refName (Correct answer)
- let-refName
Correct answer: #refName
The hash (#) prefix in a template creates a local reference variable that can be used elsewhere in the same template.
Question 2: What does the `async` pipe do when used in a template with an Observable?
- Converts the Observable to a Promise
- Subscribes and automatically unsubscribes, rendering the latest value (Correct answer)
- Delays rendering until the Observable completes
- Caches the last emitted value in local storage
Correct answer: Subscribes and automatically unsubscribes, rendering the latest value
The async pipe manages the subscription lifecycle and pushes each emitted value into the template, unsubscribing on destroy.
Question 3: In an Angular template, what does `(click)="handler($event)"` demonstrate?
- Two-way data binding
- Property binding
- Event binding with $event payload (Correct answer)
- Template reference binding
Correct answer: Event binding with $event payload
Parentheses denote event binding, and $event is the DOM event object passed to the handler function.
Question 4: Which directive would you use to repeat a block of HTML for each item in an array in Angular 17+ with the new built-in control flow?
- *ngFor
- @for (Correct answer)
- ngRepeat
- *ngRepeat
Correct answer: @for
Angular 17 introduced the @for built-in control flow block as the modern replacement for the *ngFor structural directive.
Question 5: What is the role of `trackBy` in an *ngFor directive?
- Sorts the list by a given field
- Animates items as they enter and leave
- Helps Angular identify items to minimize DOM re-renders (Correct answer)
- Filters items before rendering
Correct answer: Helps Angular identify items to minimize DOM re-renders
trackBy provides a unique identifier per item so Angular can reuse existing DOM nodes instead of destroying and recreating them.
Question 6: What is the correct way to apply multiple CSS classes conditionally using `[ngClass]`?
- [ngClass]="'class1 class2'"
- [ngClass]="{ 'class1': cond1, 'class2': cond2 }" (Correct answer)
- [ngClass]="[cond1, cond2]"
- [ngClass]="cond1 && cond2"
Correct answer: [ngClass]="{ 'class1': cond1, 'class2': cond2 }"
Passing an object literal to [ngClass] where each key is a class name and the value is a boolean expression is the standard pattern.
Question 7: Which decorator lets you listen to events on the host element of a directive or component without using the `host` metadata property?
- @HostBinding
- @HostListener (Correct answer)
- @ViewChild
- @ContentChild
Correct answer: @HostListener
@HostListener decorates a method and registers it as an event listener on the component's or directive's host element.
Which Angular template syntax creates a local template reference variable for a DOM element?