Questions 61–80 of 195 · 0 of 20 on this page marked learned
61.angular-0061Easyfresher
How does Angular protect an app against cross-site scripting (XSS), and what is the danger of bypassSecurityTrustHtml?
Angular treats every bound value as untrusted. Interpolation is escaped as text, and values bound to innerHTML, URLs, and styles are sanitized, so script tags and event handler attributes are removed. DomSanitizer.bypassSecurityTrust* turns that protection off for a value, so it must never receive user-controlled data.
Full answer
Cross-site scripting (XSS) happens when an attacker's text is run as code in another user's browser. For example, a comment field containing <img src=x onerror="stealCookies()"> is dangerous if the page inserts it as HTML.
How Angular defends:
Interpolation {{ comment }} and normal property bindings treat the value as text, not as HTML. A <script> string is shown literally.
[innerHTML]="comment" is allowed, but Angular sanitizes the value first: it keeps harmless markup (<b>, <p>) and removes scripts, event handler attributes, and unsafe URLs. In development mode, the console warns "sanitizing HTML stripped some content".
URL bindings such as [href] and [src] reject unsafe schemes such as javascript:. Style bindings and resource URLs (iframes, scripts) are restricted as well.
Templates are compiled ahead of time, so templates are not built from strings at runtime. This removes template injection.
Where apps become vulnerable:
DomSanitizer.bypassSecurityTrustHtml(value) (and ...Url, ...ResourceUrl, ...Style, ...Script). These tell Angular that you have checked the value yourself. If the value includes user input, you have created an XSS hole. A custom safeHtml pipe that always calls bypass is a common mistake.
Direct DOM access: nativeElement.innerHTML = text or document.write, which skip the sanitizer.
Server-built HTML or third-party widgets that insert markup.
Libraries with their own template compilers.
Defence in depth: send a strict Content Security Policy header, keep dependencies updated, sanitize on the server too, and store tokens carefully (see the security questions on CSRF). Never rely only on client code for security.
typescript
import { Component, computed, inject, signal } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
@Component({
selector: 'app-comment',
template: `
<!-- Escaped text: the script string is shown literally. -->
<p>{{ comment() }}</p>
<!-- Sanitized HTML: <b> stays, onerror and script are removed. -->
<div [innerHTML]="comment()"></div>
@if (videoUrl(); as url) {
<iframe [src]="url" title="Lesson video" width="320" height="180"></iframe>
}
`,
})
export class CommentComponent {
private readonly sanitizer = inject(DomSanitizer);
readonly comment = signal('<b>Nice lesson</b><img src="x" onerror="alert(1)">');
readonly videoId = signal('dQw4w9WgXcQ');
// Only an id that matches a strict pattern is used. The host is fixed in code.
readonly videoUrl = computed<SafeResourceUrl | null>(() => {
const id = this.videoId();
if (!/^[\w-]{11}$/.test(id)) {
return null;
}
return this.sanitizer.bypassSecurityTrustResourceUrl(`https://www.youtube.com/embed/${id}`);
});
}
Angular 20.3, strict template check passes. The video example builds the URL from a validated video id, not from the whole user text.
Key points
Interpolation escapes text. `[innerHTML]` is sanitized. Unsafe URL schemes are blocked.
`bypassSecurityTrust*` disables protection. Use it only on values you fully control.
Direct DOM writes skip the sanitizer.
Add a Content Security Policy and server-side checks. Angular alone is not the whole defence.
Common mistakes
Creating a pipe that bypasses sanitization for any HTML string.
Using `bypassSecurityTrustResourceUrl` with a URL built from user input for an iframe.
Assuming Angular makes the server side safe too. It only protects the client template layer.
Follow-ups
How would you safely show a YouTube video chosen by a user?
What does a Content Security Policy do for XSS?
What does the sanitizer remove from `<img src=x onerror=...>`?
Tips
Show the bypass danger with a concrete example. Interviewers look for it.
Mention defence in depth with CSP.
For the YouTube case, say you accept only an allow-listed host and build the URL yourself.
Evaluation rubric
Explains default escaping and sanitization.
Identifies the bypass methods and direct DOM access as risks.
Mentions CSP and server-side checks.
62.angular-0062Easyfresher
What can and cannot be used in an Angular template expression, and how do the safe navigation operator, nullish coalescing, non-null assertion and @let work?
Template expressions are a restricted subset of JavaScript. They support property access, method calls, ternaries, pipes, the safe navigation operator (?.), nullish coalescing (??), and the non-null assertion (!). They do not allow assignments with side effects like ++, new, arrow functions, or access to globals. @let declares a read-only template variable.
Full answer
An expression inside {{ }} or a binding is evaluated against the component class. Angular keeps the language small so that expressions stay fast and free of side effects.
Allowed:
Property reads and method calls: student().name, format(date).
Operators: arithmetic, comparison, &&, ||, !, ternary a ? b : c, nullish coalescing a ?? b.
Safe navigation user?.address?.city. If user is null or undefined the result is undefined, with no error. Signals use user()?.name.
Non-null assertion value!. It only silences the compiler (it does nothing at runtime), so use it when you know the value exists.
Pipes: {{ price | currency }}.
Newer additions: template literals (`Hello ${name}`, Angular 19.2), typeof (Angular 19), and in and exponentiation ** (Angular 20).
Not allowed:
Assignments inside interpolation, ++, --, new, bitwise operators, and chained statements with ; (event handlers allow several statements).
Arrow functions and function expressions. Move that logic into a method or a computed.
Globals such as window, Math, or console. Expose what you need as a field of the component.
@let (stable in Angular 19). @let total = price() * qty(); declares a variable that is available below it in the same template (and in nested blocks), and it updates when its inputs change. It cannot be reassigned. Use it for a value used several times, or to unwrap an Observable: @let user = user$ | async;.
Keep expressions short. A long expression is a sign to move the logic to a computed.
typescript
import { DecimalPipe } from '@angular/common';
import { Component, signal } from '@angular/core';
interface Address {
city: string;
}
interface Student {
name: string;
marks: number;
address?: Address;
}
@Component({
selector: 'app-expression-demo',
template: `
@let s = student();
@let percent = (s.marks / 150) * 100;
<p>{{ s.name }} lives in {{ s.address?.city ?? 'unknown city' }}</p>
<p>{{ percent | number: '1.0-1' }} percent</p>
<!-- Backticks and dollar signs are escaped only because this template is itself a TS template string. -->
<p>{{ \`Hello \${s.name}\` }}</p>
<p>{{ s.marks > 90 ? 'Top' : 'Average' }}</p>
<p>{{ 2 ** 3 }} {{ 'name' in s }} {{ typeof s.marks }}</p>
<p>Rounded: {{ round(percent) }}</p>
`,
imports: [DecimalPipe],
})
export class ExpressionDemoComponent {
readonly student = signal<Student>({ name: 'Asha', marks: 120 });
// Math is not available in templates, so wrap what you need.
round(value: number): number {
return Math.round(value);
}
}
Angular 20.3, strict template check passes. The `typeof`, `in`, and `**` operators need Angular 20 (template literals need 19.2).
Key points
Expressions are a safe subset of JavaScript evaluated against the component.
`?.` and `??` handle missing values. `!` only silences the compiler.
No arrow functions, `new`, globals, or `++`. Use a method or `computed`.
`@let` declares a read-only variable in a template.
Common mistakes
Using `!` to hide a possible `null` and getting a runtime error later.
Trying `Math.round(x)` in a template. `Math` is not available. Add a method or a pipe.
Writing an arrow function in a template and getting a parser error.
Follow-ups
Why are arrow functions not allowed in templates?
How is `@let` different from `*ngIf="x as y"`?
When would you move an expression into a `computed`?
Tips
Say that `!` is a compile-time tool only. This is a common trap.
Name the global-access rule and the fix.
Mention `@let` as a modern replacement for repeated expressions.
Evaluation rubric
Lists allowed and disallowed syntax correctly.
Understands ?., ??, and ! semantics.
Uses @let appropriately.
63.angular-0063Easyfresher
How do you add Angular Material to a project, use its components and forms, and customise the theme?
Run ng add @angular/material to install the package and choose a theme, then import each component you use (MatButton, MatFormField, MatInput, and so on) in the standalone component's imports. Colours and shapes are customised with the Sass theme mixins and CSS variables, not by overriding internal classes.
Full answer
Angular Material is the official component library. It follows Google's Material Design and is built on the Angular CDK (the Component Dev Kit, which holds behaviour such as overlays and accessibility helpers).
Set-up: ng add @angular/material installs the packages, adds a theme to styles.scss or styles.css, and adds the Roboto font and icon font links. Then import only what each component needs. Every Material piece is a standalone directive or component:
MatButton for <button mat-button> and mat-flat-button.
MatFormField, MatLabel, MatError, and MatInput for text fields.
MatCard, MatToolbar, MatIcon, MatTable, MatPaginator, MatDialog, MatSnackBar, MatSelect, MatCheckbox, and more.
Forms: mat-form-field wraps a native input with the matInput directive. It works with reactive forms and ngModel. It displays mat-error when the control is invalid and touched.
Services such as MatSnackBar (small messages) and MatDialog (modals) are injected and opened from code. They use the CDK overlay.
Theming. Angular Material 3 (the current design system) uses a Sass theme API. In a global style file you call mat.theme((color: (...), typography: ..., density: 0)) for a base theme, and the components read CSS variables such as --mat-sys-primary. To change one component, set its documented CSS variables. Avoid ::ng-deep overrides, which break when the library changes its internal markup.
Good habits: import components individually (this keeps the bundle small), keep accessibility features on, and check the version table: Material major versions follow the Angular major version.
Angular 20.3 with Angular Material 20.2, strict template check passes. Add the theme with `ng add @angular/material` before running it.
Key points
`ng add @angular/material` sets up the packages and theme.
Import each Material component or directive into the component that uses it.
Services like `MatSnackBar` and `MatDialog` open overlays from code.
Theme with the Sass API and CSS variables. Avoid `::ng-deep`.
Common mistakes
Importing nothing and wondering why `<mat-form-field>` is an unknown element.
Overriding internal classes with `::ng-deep`, which breaks on upgrade.
Using a Material version that does not match the Angular major version.
Follow-ups
What is the Angular CDK and how does it relate to Material?
How would you create a custom theme colour?
How do you show validation errors in a `mat-form-field`?
Tips
Mention the CDK relationship. It shows you know what is under the library.
Describe theming with CSS variables, not class overrides.
Say you import per component for bundle size.
Evaluation rubric
Knows the set-up command and per-component imports.
Uses form field and snack bar correctly.
Understands theming and version alignment.
64.angular-0064Easyfresher
Build a table that shows 5 rows per page with next and previous buttons using signals. How do you keep the logic simple and correct?
Keep the full list, the current page and the page size as signals. A computed slice gives the visible rows and a computed page count limits the buttons. Derived values always follow the source, so there is no extra state to keep in sync.
Full answer
Pagination needs three pieces of state: the full list, the page size, and the current page number. Everything else is derived:
Putting derived values in computed keeps them always correct. If the list shrinks (a filter or a delete), the current page may be beyond the last page, so clamp it. A neat way is a linkedSignal for the page, or to use Math.min(page, pageCount) in the computed that slices.
Edge cases to handle in the exercise:
An empty list: show "No rows" and keep a page count of 1.
A last page with fewer rows than the page size.
Changing page size: go back to page 1, or the current page may not exist.
Zero or negative page sizes: guard against them.
Server-side pagination is different. The list is not in memory. The server returns one page and a total count, and the page and size are query parameters. The same state model applies, but the rows come from a request (with switchMap or resource).
In the template use @for (row of rows(); track row.id) and [disabled] bound to the computed flags. For accessible tables, use <table>, <caption>, and <th scope="col">, and announce "Page 2 of 6".
Use this exercise to show that you separate state from derived data, and that you consider the edge cases without being asked.
Angular 20.3, strict template check passes. Set `pageSize` to see the last page with fewer rows.
Key points
State: list, page size, page. Everything else is `computed`.
Clamp the page when the list or size changes.
Handle empty lists, partial last pages, and invalid sizes.
Server-side paging uses the same model with a request per page.
Common mistakes
Storing `rows` as a separate signal, which can go out of sync with the list.
Not resetting to page 1 when the page size changes.
Forgetting the `track` expression on the rows.
Follow-ups
How would you add sorting without breaking pagination?
How would you change this to server-side pagination?
How would you keep the page in the URL?
Tips
State the three pieces of state out loud before coding.
Mention edge cases early. It is what separates a quick answer from a good one.
Offer the server-side version as a follow-up.
Evaluation rubric
Separates state from derived values.
Handles clamping and edge cases.
Uses control flow with `track` correctly.
65.angular-0065Easyfresher
What are smart (container) and presentational (dumb) components, and why does Angular code often split them?
A container component knows where data comes from (services, routes, stores) and passes it down. A presentational component only receives inputs, renders them, and emits outputs, so it is easy to reuse and test. The split keeps logic and display apart and works well with OnPush.
Full answer
Large components that fetch data, hold state, and draw every detail become hard to read and test. A common remedy is to split them into two kinds.
Container (smart) components:
Inject services, read route data, and talk to stores or APIs.
Hold state and decide what to do with events.
Contain little markup. Mostly they render presentational components and pass inputs.
Are usually specific to one page or feature.
Presentational (dumb) components:
Get everything through input() and communicate through output().
Do not inject feature services or know about HTTP and routing.
Often use ChangeDetectionStrategy.OnPush, since their inputs fully describe their output.
Are reusable (a student card, a pager, a price tag) and easy to test: set inputs, check the DOM, check emitted events.
A classroom example: the class teacher (container) collects marks from the exam office (service) and hands each parent (presentational card) a printed report. The card does not call the exam office. It only shows what it was given, and if a parent presses "Request review", the card sends that request back to the teacher.
Benefits: tests are small, the display can change without touching the data logic, and designers can preview presentational components in isolation (for example in Storybook).
Cautions: do not split blindly. A small feature with one component is fine. Too many layers produce files full of inputs and outputs passed through (prop drilling), which a shared service can solve. Today, signals and inject() make it easy to keep containers thin.
Explain with one realistic example, and say how you would test each part.
State the cost of the pattern so it does not sound like a rule for everything.
Mention OnPush as a natural fit.
Evaluation rubric
Describes responsibilities of both kinds.
Names benefits and costs.
Connects the pattern to testing and OnPush.
66.angular-0066Easyfresher
How do you set the page title and meta tags in Angular, and what does that mean for SEO and social sharing?
Set a title per route with the title property or a resolver, and use the Title and Meta services to update the title and meta tags from code. Crawlers and link previews mostly read the server HTML, so for public pages use server-side rendering or prerendering so these tags are present in the first response.
Full answer
Every page needs a title and a description. Browsers show the title in the tab and history, assistive technology announces it, and search engines use both in results.
Ways to set them:
Route title: { path: 'courses', component: CoursesComponent, title: 'Courses' }. The router sets document.title on navigation. A function or resolver gives a dynamic title, such as the course name. A custom TitleStrategy can add a suffix for every page.
Title service: inject(Title).setTitle('Angular basics').
Meta service: meta.updateTag({ name: 'description', content: '...' }). Social sharing uses Open Graph tags such as og:title, og:description, and og:image, set with { property: 'og:title', content: '...' }.
The important point is when the tags exist. A purely client-rendered app sends an almost empty HTML file, and tags are set only after JavaScript runs. Search engines that run JavaScript will see them, but many link-preview bots (chat apps, social networks) read only the first HTML. So for public pages use server-side rendering or prerendering. Title and Meta work on the server too, because they use the platform's document.
Good practice:
A unique title and description for each page. Keep titles under about 60 characters and descriptions under about 160.
Use updateTag (replace) instead of addTag (can create duplicates) when navigating.
Set a canonical link for pages that appear at more than one URL.
Put structured data (JSON-LD) in the page for rich results if relevant.
Do not rely on the meta keywords tag. Search engines ignore it.
typescript
import { Component, Injectable, inject } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import { RouterStateSnapshot, TitleStrategy, Routes } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class SiteTitleStrategy extends TitleStrategy {
private readonly title = inject(Title);
override updateTitle(snapshot: RouterStateSnapshot): void {
const pageTitle = this.buildTitle(snapshot);
this.title.setTitle(pageTitle ? `${pageTitle} | Schoolabe` : 'Schoolabe');
}
}
@Component({
selector: 'app-course-page',
template: `<h1>Angular basics</h1>`,
})
export class CoursePageComponent {
private readonly meta = inject(Meta);
constructor() {
this.meta.updateTag({ name: 'description', content: 'Learn Angular step by step with short lessons.' });
this.meta.updateTag({ property: 'og:title', content: 'Angular basics' });
this.meta.updateTag({ property: 'og:description', content: 'Short lessons with practice questions.' });
}
}
export const routes: Routes = [{ path: 'courses/angular', component: CoursePageComponent, title: 'Angular basics' }];
export const titleProvider = { provide: TitleStrategy, useClass: SiteTitleStrategy };
Angular 20.3, type-checked. The suffix strategy is registered with `{ provide: TitleStrategy, useClass: SiteTitleStrategy }`.
Key points
Route `title` is the simplest way. `Title` and `Meta` cover dynamic pages.
`meta.updateTag` avoids duplicates when navigating.
Link preview bots read the first HTML. Use SSR or prerendering for public pages.
Unique titles and descriptions per page.
Common mistakes
Using `addTag` on every navigation and filling the head with duplicates.
Relying on client-only rendering for pages that need link previews.
Leaving the default title for all routes.
Follow-ups
How would you add a suffix like "| Schoolabe" to every title?
How do you set a canonical URL?
How can you test that the tags appear in the server response?
Tips
Talk about when the tags exist (client versus server HTML). It is the senior part of this simple question.
Mention `TitleStrategy` for consistent titles.
Name length guidance for titles and descriptions, and say it is guidance, not a rule.
Evaluation rubric
Knows route titles and the Title and Meta services.
Explains the SSR relationship.
Avoids duplicate tag mistakes.
67.angular-0067Easyfresher
When should you use a signal and when an Observable in a modern Angular app?
Use signals for current state that templates read, because they are synchronous, always have a value, and need no subscription. Use Observables for events and asynchronous streams over time, such as HTTP, user input with debouncing, and websockets. toSignal and toObservable connect the two.
Full answer
Signals and Observables solve different problems, and a modern Angular app uses both.
A signal is a container for a current value. You read it synchronously (count()), Angular knows who read it, and the screen updates when it changes. It always has a value. There is no subscription to clean up, and computed gives cached derived values.
An Observable is a description of values arriving over time. It can emit many values, complete, or fail. It is lazy, cancellable, and has a large operator library (debounceTime, switchMap, retry, combineLatest).
Choose by the question you are asking:
"What is the current value?" Signal. Examples: the selected tab, a cart total, a loaded user.
"What happens over time?" Observable. Examples: a search box with debounce, an HTTP call with retry, a websocket feed, router events.
"Do I need cancellation, timing, or combining of streams?" Observable.
"Do I need to show a value in a template?" Convert to a signal with toSignal, or use the async pipe.
Typical pattern: keep UI state in signals, use RxJS for the asynchronous pipeline, and end the pipeline with toSignal. For simple data loading, resource and httpResource (experimental) wrap this pattern.
What not to do: do not wrap every signal in an Observable and back, and do not use a BehaviorSubject for plain state in new code. Do not call subscribe inside a component when toSignal or the async pipe can do it.
HttpClient still returns Observables, and the Angular router, forms (valueChanges), and many libraries use them, so RxJS knowledge stays necessary.
typescript
import { Component, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, map } from 'rxjs';
@Component({
selector: 'app-name-filter',
template: `
<input #box placeholder="Filter names" (input)="query.set(box.value)" />
<p>Typing: {{ query() }}</p>
<ul>
@for (n of matches(); track n) {
<li>{{ n }}</li>
}
</ul>
`,
})
export class NameFilterComponent {
private readonly names = ['Asha', 'Imran', 'Meera', 'Ishaan'];
// State: the current text.
readonly query = signal('');
// Time: wait until the user pauses, then filter. The result is a signal again.
readonly matches = toSignal(
toObservable(this.query).pipe(
debounceTime(250),
distinctUntilChanged(),
map((q) => this.names.filter((n) => n.toLowerCase().includes(q.toLowerCase()))),
),
{ initialValue: this.names },
);
}
Angular 20.3, strict template check passes. The component keeps the query in a signal, debounces through RxJS, and shows the result as a signal.
Key points
Signal: current value, synchronous, no cleanup. Observable: stream over time, lazy, cancellable.
Use RxJS for debounce, retry, cancellation, and combining streams.
End the stream with `toSignal` or the `async` pipe for the template.
Do not convert back and forth without a reason.
Common mistakes
Using a `BehaviorSubject` plus subscriptions for simple component state.
Subscribing in components and storing results in fields by hand.
Assuming signals replace RxJS completely. They do not handle timing or cancellation.
Follow-ups
How would you debounce a signal?
What does `toSignal` do with errors?
Which one would you use for a form's value changes?
Tips
Use the two questions: "current value" or "over time". They are easy to remember.
Show a realistic pairing: debounced search ending in `toSignal`.
Be balanced. Interviewers dislike "RxJS is dead" answers.
Evaluation rubric
Gives a clear selection rule.
Describes the typical combined pattern.
Avoids absolute statements.
68.angular-0068Mediummid
How does the async pipe work, why is it an impure pipe, and what are the common mistakes when using it?
The async pipe subscribes to an Observable or Promise in the template, returns the latest value, marks the view for check when a new value arrives, and unsubscribes when the view is destroyed. It must be impure because its output depends on time, not only on its input. Each use creates its own subscription, so share cold Observables.
Full answer
Pure pipes are re-evaluated only when their input changes. A pure pipe with the same input always returns the same output, so Angular can cache it. The async pipe cannot follow this rule. Its input (the Observable) stays the same while the values it produces change over time. So AsyncPipe is declared with pure: false, which means Angular calls transform on every change detection pass. This is cheap because it just returns the stored latest value.
What the pipe does internally:
On the first call it subscribes to the source and returns null (no value yet).
When a value arrives, it stores it and calls markForCheck() on the view, so OnPush components update too.
If the input reference changes to a different Observable, it unsubscribes from the old one and subscribes to the new one.
On destroy it unsubscribes. This is why it prevents leaks.
Common mistakes:
Creating a new Observable in the template on each check, such as service.load() | async. Each pass gets a new Observable, so the pipe resubscribes and fires a request every time. Create the Observable once, in a field.
Using several async pipes on the same cold Observable. Each one subscribes, so an HTTP request is sent several times. Use @if (data$ | async; as data), @let data = data$ | async;, or shareReplay.
Forgetting that the first value is null. Guard with @if or provide a loading state.
Expecting error handling. If the Observable errors, the pipe throws. Add catchError upstream.
When to prefer toSignal: it gives the same automatic cleanup and a value you can use in code and computed, and it needs no null check if you pass initialValue. The async pipe remains excellent for simple template-only cases.
Custom pipes should stay pure. Make a pipe impure only when the output depends on something other than its inputs, and then keep transform very cheap.
typescript
import { AsyncPipe } from '@angular/common';
import { Component } from '@angular/core';
import { Observable, defer, of, shareReplay } from 'rxjs';
import { delay } from 'rxjs/operators';
interface Course {
id: number;
title: string;
}
@Component({
selector: 'app-course-summary',
imports: [AsyncPipe],
template: `
<!-- One field, one shared run, several readers. -->
@let list = courses$ | async;
@if (list) {
<p>{{ list.length }} courses</p>
<ul>
@for (c of list; track c.id) {
<li>{{ c.title }}</li>
}
</ul>
} @else {
<p>Loading...</p>
}
<p>Requests sent: {{ loadCount }}</p>
`,
})
export class CourseSummaryComponent {
loadCount = 0;
// Created once. shareReplay makes later subscribers reuse the same result.
readonly courses$: Observable<Course[]> = defer(() => {
this.loadCount++;
return of([{ id: 1, title: 'Angular' }, { id: 2, title: 'RxJS' }]).pipe(delay(200));
}).pipe(shareReplay({ bufferSize: 1, refCount: true }));
// Wrong: a new Observable on every change detection pass.
// loadCourses() { return this.http.get('/api/courses'); }
// Template: loadCourses() | async
}
Angular 20.3, strict template check passes. The `loadCount` field shows that the request function runs once, not on every check, because the Observable is created in a field.
Key points
`async` is impure because its value changes over time while its input stays the same.
It subscribes, stores the latest value, calls `markForCheck`, and unsubscribes on destroy.
Create the Observable once. Several `async` pipes on a cold source mean several subscriptions.
The first emission is `null`, so handle loading. `toSignal` is the alternative.
Common mistakes
Writing `getCourses() | async` where the method returns a new Observable every time.
Using `| async` three times on an HTTP Observable and sending three requests.
Making a custom pipe impure to hide a stale view caused by mutation.
Follow-ups
How does the async pipe update an OnPush component?
How can you share one subscription between several async pipes?
When would you choose `toSignal` over the `async` pipe?
Tips
Explain the reason for impurity in one sentence: input does not change, output does.
Describe the method-call pitfall. It is the most common real bug.
Mention `@let` and `shareReplay` as fixes for double subscriptions.
Evaluation rubric
Explains pure versus impure correctly and why async is impure.
Knows subscription and cleanup behaviour.
Identifies the double subscription and new-Observable pitfalls.
69.angular-0069Mediummid
How do combineLatest, forkJoin, zip and withLatestFrom differ, and when do you use each?
forkJoin waits for all sources to complete and emits their last values once, which suits several HTTP calls. combineLatest emits whenever any source emits, using the latest value of each, which suits live state. zip pairs values by position. withLatestFrom lets one stream sample the latest value of another without being triggered by it.
Full answer
All four combine several Observables, but they decide differently when to emit.
forkJoin([a$, b$]): waits until every source completes, then emits one array with the last value of each, then completes. If any source errors, the result errors. If a source completes without emitting, nothing is emitted. Use it for "run these independent requests and continue when all are done". It does not suit streams that never complete.
combineLatest([a$, b$]): emits the first time every source has emitted at least once, then emits again each time any source emits, using the latest values of all. Use it for derived state from several live inputs, such as a filter, a sort order, and a list. It completes when all sources complete.
zip([a$, b$]): pairs the nth value from each source. It emits only when each source has produced its nth value, so the slowest source sets the pace. Use it rarely: for lock-step pairing such as questions with answers.
source$.pipe(withLatestFrom(other$)): the source drives the emissions. When it emits, the latest value of other$ is attached. Changes in other$ alone emit nothing. Use it for "when the user clicks save, send the form together with the current user".
Rules to remember:
forkJoin requires completion. For HTTP this is automatic.
combineLatest emits nothing until all sources have a value. Use startWith to unblock a source that may not emit.
Dictionary form is more readable: forkJoin({ user: user$, courses: courses$ }).
With signals, computed replaces combineLatest for state that already lives in signals.
The script below uses timers to make the timing visible. Output is the same every run.
typescript
import { combineLatest, forkJoin, interval, lastValueFrom, map, of, take, timer, toArray, withLatestFrom, zip } from 'rxjs';
const slow$ = timer(30).pipe(map(() => 'slow'));
const fast$ = timer(10).pipe(map(() => 'fast'));
// forkJoin: one emission after both complete.
console.log('forkJoin ', await lastValueFrom(forkJoin({ a: slow$, b: fast$ })));
// combineLatest: emits after each source has a value, then on every change.
const letters$ = interval(20).pipe(take(3), map((n) => 'ABC'[n]));
const numbers$ = interval(35).pipe(take(2), map((n) => n + 1));
console.log('combineLatest', await lastValueFrom(combineLatest([letters$, numbers$]).pipe(toArray())));
// zip: pairs by position, so the third letter has no partner.
const left$ = of('a', 'b', 'c');
const right$ = of(1, 2);
console.log('zip ', await lastValueFrom(zip(left$, right$).pipe(toArray())));
// withLatestFrom: the source drives. Changes of the other stream alone emit nothing.
const clicks$ = timer(50, 45).pipe(take(2), map((n) => `click${n + 1}`));
const user$ = timer(0, 30).pipe(take(4), map((n) => `user${n}`));
console.log('withLatestFrom', await lastValueFrom(clicks$.pipe(withLatestFrom(user$), toArray())));
Tested with RxJS 7 under Node 22.18 or newer (`node main.ts`, package.json with `type: module`), run twice with identical output.
Key points
`forkJoin`: once, after all complete. Good for parallel HTTP.
`combineLatest`: on every change, latest of each. Good for live derived state.
`zip`: pairs by position. `withLatestFrom`: sampling driven by the source stream.
`combineLatest` waits for every source to emit once. Use `startWith` where needed.
Common mistakes
Using `forkJoin` with a stream that never completes, such as `valueChanges`, so nothing is ever emitted.
Expecting `combineLatest` to emit before every source has a value.
Using `combineLatest` where `withLatestFrom` is needed, so a change in the second stream triggers an unwanted action.
Follow-ups
How would you load a user and their courses in parallel and show both?
What does `zip` do if one source is much faster than the other?
How would you replace `combineLatest` with signals?
Tips
Use the HTTP example for `forkJoin` and a filter UI example for `combineLatest`.
Mention the completion requirement of `forkJoin`. Interviewers ask about it.
Give the dictionary form, because it is more readable.
Evaluation rubric
Explains emission rules of all four.
Matches each to a realistic use.
Knows pitfalls (completion, initial emissions).
70.angular-0070Mediummid
How does NgRx Store work, including actions, reducers, selectors and feature state, and how do you set it up in a standalone app?
NgRx Store keeps app state in one immutable object. Components dispatch actions (events), pure reducer functions create the next state, and memoized selectors read slices of it. In a standalone app you register it with provideStore and provideState, and read data with store.selectSignal.
Full answer
NgRx is the Redux pattern for Angular. The cycle is: a component dispatches an action, a reducer computes the new state from the old state and the action, the store holds that state, and components select what they need.
Parts:
Actions describe what happened, not how state changes: [Courses Page] Load, [Courses API] Load Success. createActionGroup makes a group with typed props.
Reducers are pure functions (state, action) => newState. They never mutate and never do side effects. createReducer(initialState, on(action, (state, props) => ({...state, ...}))).
Selectors are functions that read and derive data from state. createSelector memoizes: it recomputes only when its inputs change by reference. createFeature generates selectors for each field of a feature state for you.
The store: inject(Store) and store.dispatch(action). store.selectSignal(selector) returns a signal. store.select(selector) returns an Observable.
Set-up in a standalone app: provideStore() in ApplicationConfig, and provideState(coursesFeature) for each feature (it can be added to route providers for lazy features). The Redux DevTools extension works with provideStoreDevtools().
Why use it: a single source of truth, predictable state changes, time-travel debugging, and clear logs of "what happened". Costs: boilerplate and indirection. Keep UI-only state out of the store. Do not put server cache and form drafts there without a reason. Keep state normalized, so updates do not need deep copies, and store plain serializable data.
Signals in the store: selectSignal works well with OnPush and computed. For smaller features, NgRx SignalStore gives similar structure with less boilerplate.
Angular 20.3 with NgRx 20.1, strict template check passes. The reducer is a pure function and can be tested without Angular.
Key points
Actions are events, reducers are pure state transitions, selectors read and memoize.
`createFeature` generates the feature selectors. `createActionGroup` types the actions.
Register with `provideStore` and `provideState`. Read with `selectSignal`.
Pay the boilerplate cost only where traceability matters.
Common mistakes
Mutating state in a reducer, for example `state.items.push(x)`.
Calling an API from a reducer. Side effects belong in effects.
Putting every piece of UI state in the store.
Follow-ups
Why must reducers be pure?
What does memoization in `createSelector` buy you?
How would you register a feature state for a lazy route?
Tips
Describe the loop (dispatch, reduce, select) first, then name each piece.
Be honest about cost, and say when you would pick SignalStore or a service instead.
Mention immutability and serializable state.
Evaluation rubric
Explains actions, reducers, selectors, and store flow.
Shows set-up in standalone APIs.
Gives a balanced view of costs.
71.angular-0071Mediummid
What are NgRx Effects, how do you write a functional effect that loads data, and how do you choose between switchMap, exhaustMap and concatMap in effects?
An effect listens to dispatched actions, performs a side effect such as an HTTP call, and dispatches new actions with the result. A functional effect is written with createEffect and inject. Effects use flattening operators, so the choice of switchMap, exhaustMap or concatMap decides how overlapping requests behave.
Full answer
Reducers must be pure, so anything else (HTTP, storage, timers, navigation) lives in effects. An effect is an Observable of actions in, actions out.
Actions is the stream of all dispatched actions. ofType filters it.
Default parameters with inject() give the effect its dependencies in a plain function. Class-based effects (@Injectable with createEffect fields) are the older style and still common.
The catchError is inside the inner Observable, so one failure does not kill the effect stream. This is the most common effect bug.
Effects are registered with provideEffects({ loadCourses }) (functional) or provideEffects(MyEffects) (class).
Effects that only do a side effect without dispatching, such as logging, use { dispatch: false }.
Choosing the flattening operator:
switchMap: latest wins, for reads such as search. It cancels the older request.
exhaustMap: ignore new triggers while one is running. Good for loading on button press, login, and refresh clicks.
concatMap: queue in order. Good for writes where order matters.
mergeMap: parallel, with no order guarantee. Good for independent writes.
Testing: use provideMockActions(() => actions$) from @ngrx/effects/testing, feed an action, and check the emitted result. No store is needed.
Keep effects small and the actions meaningful. An effect that dispatches an action that triggers another effect that dispatches another is hard to follow.
Angular 20.3 with NgRx 20.1, type-checked. A Karma spec in headless Chrome runs the `loadCourses` effect with `provideMockActions` for both the success path and an API error that becomes a failure action. The API service is a fake with fixed data.
Key points
Effects turn actions into side effects and new actions. Reducers stay pure.
Put `catchError` inside the inner Observable.
Pick `switchMap`, `exhaustMap`, `concatMap`, or `mergeMap` by how overlap should behave.
Test with `provideMockActions`. Register with `provideEffects`.
Common mistakes
Putting `catchError` on the outer stream, which stops the effect after the first error.
Using `switchMap` for save operations, which can cancel a write.
Chains of effects that trigger each other, which are hard to debug.
Follow-ups
Why does an effect need `catchError` on the inner stream?
How would you run an effect on application start?
How do you test an effect without a store?
Tips
Show the inner catchError placement first. It proves understanding.
Tie operator choice to the user action (read, button press, write).
Mention functional effects as the current style and class effects as legacy.
Evaluation rubric
Writes a functional effect with the correct structure.
Chooses flattening operators with reasons.
Knows how to test effects.
72.angular-0072Mediummid
What is NgRx SignalStore, and how do withState, withComputed, withMethods, rxMethod and patchState fit together?
SignalStore builds a store service from composable features. withState defines state as signals, withComputed adds derived values, withMethods adds the operations that change state through patchState, and rxMethod connects RxJS pipelines such as an HTTP load to the store. It gives structure with much less boilerplate than the classic Store.
Full answer
signalStore returns an injectable class made from features, in order. Each feature can use what earlier features added.
withState turns every top-level property into a signal (store.courses()) and keeps the state object as a deep signal. Properties are read-only for outsiders.
withComputed adds derived signals.
withMethods adds methods. State is changed only through patchState(store, { ... }) or with an updater function, which keeps changes in one place. The state stays protected from outside writes by default.
rxMethod<T>(pipe(...)) creates a method that accepts a value, a signal, or an Observable and runs an RxJS pipeline. It is how you debounce, switchMap to an API call, and tap the result into state. It cleans up with the store.
withHooks runs code when the store is created or destroyed.
providedIn: 'root' makes it global. Without it, put the store in providers of a route or component to scope the state to that tree.
Extra packages add features: withEntities for collections and signalStoreFeature for reusable custom features, such as a shared loading state.
When to use it: component or feature state that needs structure, but not the ceremony of actions, reducers, and effects. When to prefer the classic Store: large teams that want strict action logs, DevTools time travel, and cross-feature event handling.
Testing is simple: create the store with TestBed, call methods, and check signals. Fake the API in providers.
Angular 20.3 with NgRx Signals 20.1 and NgRx Operators 20.1, type-checked. A Karma spec in headless Chrome checks that `onInit` loads the courses, that `setQuery` filters `visible`, and that a failing API sets the error message. `tapResponse` handles success and error inside the inner Observable.
Key points
Features compose in order: state, computed, methods, hooks.
Change state only through `patchState`. Outsiders see read-only signals.
`rxMethod` connects RxJS pipelines (debounce, `switchMap`, HTTP) to the store.
Scope the store with `providers`, or make it global with `providedIn: 'root'`.
Common mistakes
Writing to state from components instead of calling store methods.
Forgetting error handling inside `rxMethod`, so one failed request ends the pipeline.
Putting unrelated features into one global store.
Follow-ups
How does `rxMethod` differ from calling `subscribe` yourself?
How would you share a loading and error feature between stores?
How do you test a SignalStore?
Tips
Contrast it with the classic Store by naming what you gain (less code) and lose (action log).
Show `patchState` as the single door for state changes.
Mention scoping with `providers`.
Evaluation rubric
Explains each feature function in order.
Uses rxMethod with error handling.
Knows when to choose it over the classic Store.
73.angular-0073Mediummid
What is httpResource, how does it differ from HttpClient used with toSignal, and what is its status?
httpResource is a signal-based wrapper over HttpClient. You give it a function that returns the request, and it fetches again when the signals read in that function change, exposing value, status, error, isLoading and reload as signals. It is experimental in Angular 19 and 20 and is meant for reads, not writes.
Full answer
httpResource is built on resource and HttpClient. It uses the same pipeline, including interceptors, so authentication and error handling still apply.
The function is reactive. When this.query() changes, a new request is sent and the previous one is cancelled.
If the function returns undefined, the resource stays idle and sends nothing. This handles "no id yet".
Result signals: value(), status() (idle, loading, reloading, resolved, error, local), error(), isLoading(), headers(), and hasValue(). reload() runs the request again.
Variants for other response types: httpResource.text(), httpResource.blob(), and httpResource.arrayBuffer().
parse validates and converts the response. The generic type is not checked at runtime, so a parse function (written by hand or with a schema library such as Zod) is the safe approach.
The value can be set locally with set() and update(), which is handy for optimistic updates.
Compared with toSignal(http.get(...)): the old way needs toObservable, switchMap, a manual loading flag, and an error flag. httpResource provides all of it for the common case. For debounce, retries with backoff, polling, or merging streams, RxJS is still better, and you can combine both.
Status: httpResource and resource are experimental in Angular 19 and 20, so the API can change in minor versions. Use them with that in mind, and keep usage in a few wrapper services so a later change is cheap.
Important: it is for reading data. Use HttpClient directly for POST, PUT, and DELETE.
typescript
import { httpResource } from '@angular/common/http';
import { Component, signal } from '@angular/core';
interface Course {
id: number;
title: string;
}
function parseCourses(raw: unknown): Course[] {
if (!Array.isArray(raw)) {
throw new Error('Expected a list of courses');
}
return raw.map((item) => {
const row = item as Partial<Course>;
if (typeof row.id !== 'number' || typeof row.title !== 'string') {
throw new Error('Invalid course');
}
return { id: row.id, title: row.title };
});
}
@Component({
selector: 'app-course-finder',
template: `
<input #box placeholder="Search" (input)="query.set(box.value)" />
<button (click)="courses.reload()">Reload</button>
@if (courses.isLoading()) {
<p>Loading...</p>
} @else if (courses.error(); as err) {
<p role="alert">Failed: {{ err.message }}</p>
} @else if (courses.hasValue()) {
<ul>
@for (c of courses.value(); track c.id) {
<li>{{ c.title }}</li>
} @empty {
<li>No courses</li>
}
</ul>
}
`,
})
export class CourseFinderComponent {
readonly query = signal('');
readonly courses = httpResource<Course[]>(
() => ({
url: '/api/courses',
params: { q: this.query() },
}),
{ parse: parseCourses, defaultValue: [] },
);
}
Angular 20.3 (experimental API, may change). It needs `provideHttpClient()`. The `parse` function checks the shape before the data reaches the template.
Key points
Reactive request function. A signal change cancels the old request and starts a new one.
Provides `value`, `status`, `error`, `isLoading`, `reload`, and local `set`.
Use `parse` to validate the response. The generic type is only a hint.
Experimental in Angular 19 and 20. Reads only.
Common mistakes
Using `httpResource` to send a POST or DELETE.
Reading `value()` while the resource is in an error state, which throws.
Trusting the generic type as validation.
Follow-ups
How does it differ from `resource` with `fetch`?
How would you debounce the query that drives an `httpResource`?
How do interceptors apply to it?
Tips
State the experimental status in your first sentence.
Compare it with the toObservable plus switchMap plus toSignal pattern.
Mention `parse` for runtime validation.
Evaluation rubric
Explains reactive requests and cancellation.
Lists state signals and variants.
States status and limits honestly.
74.angular-0074Mediummid
How do you write a custom structural directive, and what do TemplateRef, ViewContainerRef, the context object and the template guard do?
A structural directive receives the template it is attached to as a TemplateRef and decides whether and how often to render it through ViewContainerRef.createEmbeddedView. The asterisk syntax is sugar for an ng-template. A context object provides variables such as let-index, and ngTemplateContextGuard gives those variables correct types.
Full answer
*appRepeat="3" is shorthand. Angular rewrites it to <ng-template [appRepeat]="3">...</ng-template>. A structural directive injects that template and renders it zero or more times.
The pieces:
TemplateRef<C> is the template with its context type C.
ViewContainerRef is the place where views are inserted. createEmbeddedView(templateRef, context) creates one, and clear() removes all of them.
The context is an object. $implicit is the default value for let-item, and other keys are named: let-i="index".
input() gives the directive's value (appRepeat). Inside an effect, the directive re-renders when the input changes.
static ngTemplateContextGuard is a type guard that tells the compiler the shape of the context, so let-i="index" is typed as a number rather than any. ngTemplateGuard_appRepeat can narrow the input type as ngIf does.
Microsyntax lets users write *appRepeat="3; let i = index". The part after the first ; binds context names. An extra input can be bound with the directive's selector prefix: *appRepeat="3; gap: 10" sets an input named appRepeatGap.
When to write one: a reusable structure that control flow cannot express, such as role-based rendering (*appHasRole="'admin'"), a permissions check, or a template with repeated context. When not: for conditions and loops, @if and @for are faster and typed already, and the old *ngIf and *ngFor are legacy.
Remember to destroy views you create. clear() does it, and the container destroys remaining views when the directive is destroyed.
typescript
import { Component, Directive, TemplateRef, ViewContainerRef, effect, inject, input } from '@angular/core';
interface RepeatContext {
$implicit: number;
index: number;
count: number;
}
@Directive({ selector: '[appRepeat]' })
export class RepeatDirective {
readonly times = input.required<number>({ alias: 'appRepeat' });
private readonly template = inject(TemplateRef<RepeatContext>);
private readonly container = inject(ViewContainerRef);
constructor() {
effect(() => {
const count = Math.max(0, Math.floor(this.times()));
this.container.clear();
for (let i = 0; i < count; i++) {
this.container.createEmbeddedView(this.template, { $implicit: i + 1, index: i, count });
}
});
}
// Gives the compiler the context type, so let-index is a number.
static ngTemplateContextGuard(_dir: RepeatDirective, _ctx: unknown): _ctx is RepeatContext {
return true;
}
}
@Component({
selector: 'app-rows',
imports: [RepeatDirective],
template: `
<ul>
<li *appRepeat="3; let n; let i = index; let total = count">Row {{ n }} (index {{ i }} of {{ total }})</li>
</ul>
`,
})
export class RowsComponent {}
Angular 20.3, strict template check passes. A Karma test in headless Chrome renders the repeat three times and checks the text of the last row. Use as `<p *appRepeat="3; let i = index">Row {{ i }}</p>`.
Key points
`*dir` is sugar for `<ng-template [dir]>`.
`TemplateRef` plus `ViewContainerRef.createEmbeddedView(template, context)` renders the content.
`$implicit` and named keys form the context. `ngTemplateContextGuard` types them.
Prefer built-in control flow unless you need custom structure.
Common mistakes
Forgetting `clear()` before re-rendering, which duplicates content.
Leaving the context untyped, so every `let-` variable is `any`.
Writing a structural directive for a plain condition that `@if` handles.
Follow-ups
How does Angular desugar `*appRepeat="3; let i = index"`?
How does `ngIf` narrow the type of its input?
How would you add an else template?
Tips
Show the desugared form to prove you know what the asterisk does.
Mention the type guard. It is the detail that separates a quick answer from a complete one.
Say that for conditions you would use `@if`.
Evaluation rubric
Understands the template and container model.
Uses context and microsyntax correctly.
Knows when not to write one.
75.angular-0075Mediummid
How does internationalisation (i18n) work in Angular, including the i18n attribute, ICU plural expressions, $localize and locale-aware pipes?
Angular's built-in i18n marks text with the i18n attribute or $localize, extracts it to a translation file with ng extract-i18n, and the build produces one app per locale with the translations compiled in. ICU expressions handle plural and select forms, and pipes such as date and currency follow the locale.
Full answer
Internationalisation (i18n) makes an app ready for several languages. Localisation is adding the actual translations.
Build-time workflow with Angular's own tools:
Mark text in templates with the i18n attribute: <h1 i18n="@@welcomeTitle">Welcome</h1>. The text after @@ is a custom id that keeps the id stable when the text changes. Attributes use i18n-title, i18n-placeholder, and so on.
In TypeScript use the tagged template $localize: $localize`:@@saveLabel:Save`. It needs the @angular/localize package (added with ng add @angular/localize).
Plurals and gender use ICU expressions in the template: {count, plural, =0 {No lessons} =1 {One lesson} other {{{count}} lessons}}. Different languages have different plural rules, and ICU lets the translator write them.
ng extract-i18n creates a source file (XLIFF, XMB, or JSON). Translators produce one file per language.
Declare locales in angular.json under i18n (source locale and each translation file) and build with "localize": true. The build creates a separate bundle per locale, with translations inserted at compile time. This is fast at runtime, but you deploy one folder per locale and switching language reloads the page.
Locale data: pipes such as date, currency, number, and percent use LOCALE_ID. Localised builds set it automatically. For a runtime-only approach you call registerLocaleData(...) and provide LOCALE_ID.
Alternatives: runtime libraries such as Transloco or ngx-translate load JSON files and switch language without a reload, at the cost of a small runtime and no compile-time check. Choose built-in i18n for performance and strictness, and a runtime library when users must change language instantly or translations change often.
Do not build sentences by joining pieces. Word order differs between languages, so translate whole messages with placeholders.
Angular 20.3, type-checked. The `angular.json` settings are shown in the comment. Run `ng extract-i18n` to produce the translation source file.
Key points
Mark text with `i18n`, `i18n-attr`, or `$localize`, then run `ng extract-i18n`.
ICU expressions handle plural and select forms.
The built-in approach compiles one bundle per locale. Runtime libraries switch without reload.
Pipes use `LOCALE_ID`. Never concatenate translated fragments.
Common mistakes
Joining translated words into a sentence in code, which breaks in other languages.
Forgetting custom ids, so every text edit invalidates the translation.
Hard-coding date or currency formats instead of using pipes.
Follow-ups
How would you let a user change language without reloading?
How are plurals different in Arabic or Russian compared with English?
How do you serve each locale's build from the server?
Tips
Describe both workflows (compile time and runtime) and give a rule for choosing.
Mention ICU for plurals. It shows you have dealt with real translation.
Mention custom ids and the translator hand-off.
Evaluation rubric
Knows the i18n attribute, $localize, extraction, and per-locale builds.
Understands ICU and locale-aware pipes.
Can compare with runtime libraries.
76.angular-0076Mediummid
How do you animate elements entering and leaving the page in Angular, and what changed with animate.enter and animate.leave?
Since Angular 20.2 you animate entering and leaving elements with the animate.enter and animate.leave bindings, which apply CSS classes and wait for the animation to finish before removing the element. The older @angular/animations package (trigger, state, transition) is deprecated and planned for removal, so use it only to maintain existing code.
Full answer
Before Angular 20.2, animation in Angular meant the @angular/animations package: a trigger with state and transition definitions in the component metadata, [@trigger] bindings in the template, and provideAnimationsAsync() in the app config. It worked, but it added to the bundle and used its own timeline engine on top of the browser.
From Angular 20.2 the recommended way uses plain CSS:
animate.enter="fade-in" adds the class when the element is inserted, and removes it when the animation ends.
animate.leave="fade-out" keeps the element in the DOM, adds the class, and removes the element after the animation completes (Angular waits for the longest CSS animation or transition).
Both accept a string, an array of classes, or a function for libraries such as GSAP. A leave function must call the completion callback, or Angular removes the element after a timeout of four seconds.
No import and no provider are needed. They are compiler features that work with @if and @for.
Other ordinary changes (hover effects, state changes) use normal CSS transitions with class and style bindings. Reordering and layout animations can use the browser's View Transitions API through the router.
The @angular/animations package is deprecated as of Angular 20.2, with removal planned for a later major version. Do not mix both systems in the same component. Migrate gradually, and remove provideAnimationsAsync when the last trigger is gone, which also reduces the bundle.
Accessibility: respect prefers-reduced-motion in CSS, and do not hide meaning in motion alone.
Angular 20.3, strict template check passes. The second component is the legacy style, kept to show what existing code looks like. It needs `provideAnimationsAsync()` from `@angular/platform-browser/animations/async`.
Key points
`animate.enter` and `animate.leave` bind CSS classes. Angular waits for leave animations before removal.
No provider or package is needed. They work with `@if` and `@for`.
`@angular/animations` is deprecated from 20.2. Keep it only for existing code. Do not mix both in one component.
Honour `prefers-reduced-motion`.
Common mistakes
Forgetting to call the completion function in a function-based `animate.leave`, which delays removal.
Mixing legacy triggers and `animate.*` in one component.
Animating layout properties such as `height` when `transform` and `opacity` would be smoother.
Follow-ups
How would you animate items of a list as they are removed?
How do you disable animations for users who prefer reduced motion?
How would you migrate a `:enter` and `:leave` transition to the new API?
Tips
State the version where it changed (20.2) and the status of the old package.
Say that CSS does the work, so you can use any CSS skills.
Mention reduced motion without being asked.
Evaluation rubric
Uses animate.enter and animate.leave correctly.
Describes the legacy package and its deprecation.
Considers accessibility and performance.
77.angular-0077Mediummid
How do you build an accessible popup with the Angular CDK Overlay, a focus trap and the LiveAnnouncer?
The CDK Overlay renders content above the page in a positioned container. A position strategy anchors it to a trigger, a scroll strategy decides what happens on scroll, and a backdrop can close it on outside clicks. Add cdkTrapFocus to keep keyboard focus inside, close on Escape, return focus to the trigger, and announce changes with LiveAnnouncer.
Full answer
The Component Dev Kit (CDK) holds the behaviour behind Angular Material without the styling. The Overlay module is the base for menus, tooltips, dialogs, and autocomplete panels.
Parts:
Overlay.create(config) returns an OverlayRef. Config includes positionStrategy, scrollStrategy, hasBackdrop, and panel class names.
Position strategy: overlay.position().flexibleConnectedTo(triggerElement).withPositions([...]) anchors the panel to a trigger and flips it when there is no room. .global().centerHorizontally() is for dialogs.
Scroll strategy: reposition() follows the trigger, block() stops page scroll, and close() closes on scroll.
Portals: TemplatePortal or ComponentPortal is the content you attach with overlayRef.attach(portal).
overlayRef.backdropClick(), keydownEvents(), and outsidePointerEvents() are streams for closing.
Always call overlayRef.dispose(), or the panel and its listeners stay in the page.
Accessibility pieces from @angular/cdk/a11y:
cdkTrapFocus keeps Tab and Shift+Tab inside the popup. cdkTrapFocusAutoCapture moves focus into it when it opens and restores focus to the previously focused element (the trigger) when it closes.
LiveAnnouncer.announce('Menu opened') writes to a hidden live region that screen readers read.
Give the panel a role (dialog or menu), a label, and close it on Escape.
For a real product, use the ready-made Dialog (from the CDK) or MatDialog, and use the Overlay directly for custom widgets. Test with a keyboard first.
For modals, set aria-modal="true", and make the page behind inert if possible.
Angular 20.3 with CDK 20.2, strict template check passes. Press Escape or click outside to close.
Key points
`Overlay.create` plus a position strategy, a scroll strategy, and a portal builds a popup.
`cdkTrapFocus` with auto capture handles focus in and out. Close on Escape.
`LiveAnnouncer` tells screen readers about changes.
Always `dispose()` the overlay.
Common mistakes
Not disposing the overlay, leaving listeners and DOM nodes behind.
Opening a popup without moving focus into it, or not returning focus afterwards.
Positioning with absolute CSS values that break when the page scrolls.
Follow-ups
How does `flexibleConnectedTo` choose among positions?
When would you use `ComponentPortal` instead of `TemplatePortal`?
How do you make the rest of the page inert while a modal is open?
Tips
Say you would use the CDK or Material Dialog for ordinary dialogs, and Overlay for custom widgets.
Mention focus return. It is the most commonly missed detail.
Name `dispose()` and cleanup.
Evaluation rubric
Explains position, scroll, backdrop, and portal concepts.
Uses cdkTrapFocus and LiveAnnouncer correctly.
Closes and cleans up properly.
78.angular-0078Mediummid
Build a long list with the CDK virtual scroll that loads more items when the user nears the end. How does virtual scrolling work and what are its limits?
Virtual scrolling renders only the rows that are visible plus a small buffer, and positions them inside a container whose scroll height matches the full list. With cdk-virtual-scroll-viewport and *cdkVirtualFor, you set a fixed item size, a fixed viewport height, and load the next page when the rendered range reaches the end.
Full answer
Rendering 50,000 rows creates 50,000 DOM nodes, which makes scrolling and updates slow and uses a lot of memory. Virtual scrolling renders only what the user can see.
How it works: the viewport has a fixed height and a spacer that is as tall as the whole list would be (itemSize times the item count). On scroll, the CDK calculates which indexes are visible, renders those plus a buffer, and moves them to the right offset with a transform. The browser sees a few dozen nodes, but the scroll bar looks like a full list.
Set-up:
Import ScrollingModule (or the standalone directives).
<cdk-virtual-scroll-viewport itemSize="48" class="viewport"> with a CSS height. Without a height nothing renders.
*cdkVirtualFor="let row of rows(); trackBy: trackById" instead of @for.
FixedSizeVirtualScroll is the default strategy, so every row must have the same height. For variable heights the CDK offers an experimental autosize strategy, or use the Material or ngx-virtual-scroller alternatives.
Infinite loading: listen to (scrolledIndexChange), or read viewport.getRenderedRange().end. When end is near rows().length (for example within 10 rows) and no request is in flight, request the next page and append it with a new array ([...old, ...next]). Guard with a loading flag and an allLoaded flag, and handle errors with a retry button.
Limits and trade-offs:
Browser find (Ctrl+F) cannot find text in rows that are not rendered.
Screen readers see only rendered rows, so provide aria-rowcount, aria-setsize, or a text summary for accessibility.
Variable row heights, expanding rows, and sticky headers need extra work.
For lists under a few hundred rows, plain @for is simpler and enough.
Pagination can be better than infinite scroll when users need to find a position or reach the footer.
Angular 20.3 with CDK 20.2, strict template check passes. The fake loader waits 300 ms and returns 50 more rows, up to 200.
Key points
Render only the visible rows and use a spacer for the full height.
Needs a fixed viewport height and a fixed item size with the default strategy.
Load more when the rendered range nears the end, with `loading` and `allLoaded` guards.
Costs: browser find, accessibility, and variable heights are harder.
Common mistakes
Forgetting to give the viewport a height, so nothing renders.
Requesting the next page repeatedly while one request is in flight.
Mutating the array with `push`, so the viewport does not update.
Follow-ups
How would you support rows of different heights?
How would you keep screen reader users informed about the list size?
When would you choose pagination over infinite scroll?
Tips
Describe the technique (spacer plus rendered window) in one sentence.
State the limits. A solution without trade-offs sounds untested.
Mention guards for repeated loads.
Evaluation rubric
Understands how the virtualisation works.
Implements loading with guards correctly.
Mentions accessibility and when not to use it.
79.angular-0079Mediummid
How do you build a reorderable list with the CDK drag and drop module, and how do you make it keyboard accessible?
Put cdkDropList on the container and cdkDrag on each item, then handle the cdkDropListDropped event by calling moveItemInArray on a copy of your data. Moving between lists uses transferArrayItem. The CDK does not provide keyboard reordering, so add explicit move up and move down buttons.
Full answer
The CDK drag and drop module handles pointer and touch dragging, animation, auto-scroll, and placeholder preview. You supply the data change.
Basic set-up:
Import CdkDropList and CdkDrag (or DragDropModule).
<ul cdkDropList (cdkDropListDropped)="drop($event)"> and <li cdkDrag> for each item.
The event gives previousIndex and currentIndex. In the handler, move the item in your data. moveItemInArray(array, from, to) mutates the array it receives. With signals, copy first: this.items.update(list => { const next = [...list]; moveItemInArray(next, e.previousIndex, e.currentIndex); return next; }).
Between two lists use cdkDropListGroup or [cdkDropListConnectedTo] and transferArrayItem(previousData, currentData, previousIndex, currentIndex). Give each list its data with [cdkDropListData].
Useful options: cdkDragHandle (drag only by a grip icon), cdkDragDisabled, cdkDragPreview and cdkDragPlaceholder templates, cdkDropListOrientation="horizontal", and cdkDropListLockAxis.
Accessibility: dragging needs a pointer. The CDK drag-drop does not support keyboard reordering. A complete solution gives the same action another way: "Move up" and "Move down" buttons that call the same move function, with a label naming the item, and an announcement (LiveAnnouncer) of the new position. Also persist the new order on the server and handle failures by restoring the old order.
Performance notes: for hundreds of items combine with virtual scroll carefully (the CDK has limited support), or use pagination. Use track with a stable id in @for.
typescript
import { CdkDrag, CdkDragDrop, CdkDragHandle, CdkDropList, moveItemInArray } from '@angular/cdk/drag-drop';
import { LiveAnnouncer } from '@angular/cdk/a11y';
import { Component, inject, signal } from '@angular/core';
@Component({
selector: 'app-priority-list',
imports: [CdkDropList, CdkDrag, CdkDragHandle],
template: `
<ul cdkDropList (cdkDropListDropped)="drop($event)" aria-label="Study topics in priority order">
@for (topic of topics(); track topic; let i = $index; let first = $first; let last = $last) {
<li cdkDrag class="item">
<span cdkDragHandle aria-hidden="true">::</span>
{{ i + 1 }}. {{ topic }}
<button type="button" [disabled]="first" (click)="move(i, i - 1)" [attr.aria-label]="'Move ' + topic + ' up'">Up</button>
<button type="button" [disabled]="last" (click)="move(i, i + 1)" [attr.aria-label]="'Move ' + topic + ' down'">Down</button>
</li>
}
</ul>
`,
styles: `
.item { display: flex; gap: 8px; padding: 6px; border: 1px solid #ccc; background: white; }
`,
})
export class PriorityListComponent {
private readonly announcer = inject(LiveAnnouncer);
readonly topics = signal(['Signals', 'Routing', 'Forms', 'Testing']);
drop(event: CdkDragDrop<string[]>): void {
this.move(event.previousIndex, event.currentIndex);
}
move(from: number, to: number): void {
if (to < 0 || to >= this.topics().length || from === to) {
return;
}
this.topics.update((list) => {
const next = [...list];
moveItemInArray(next, from, to);
return next;
});
void this.announcer.announce(`${this.topics()[to]} moved to position ${to + 1}`);
}
}
Angular 20.3 with CDK 20.2, strict template check passes. The move buttons call the same function as the drop handler.
Key points
`cdkDropList` on the container, `cdkDrag` on the items, handle `cdkDropListDropped`.
`moveItemInArray` mutates, so copy first when the data lives in a signal.
`transferArrayItem` and connected lists move items between lists.
Provide keyboard buttons and announcements, because dragging is pointer-only.
Common mistakes
Mutating the signal's array in place, so the view does not refresh.
Providing drag as the only way to reorder.
Not using a stable `track` expression, which breaks the drag animation.
Follow-ups
How would you build a kanban board with three columns?
How would you save the new order and handle a failed save?
How would you limit dragging to a handle?
Tips
Raise the keyboard alternative yourself. It shows you think about all users.
Mention the copy-before-move rule for signals.
Describe optimistic update with rollback for saving.
Evaluation rubric
Uses the drag and drop directives and event correctly.
Updates signal state immutably.
Provides an accessible alternative.
80.angular-0080Mediummid
Build an accessible typeahead (autocomplete) with a reactive form control. How do you handle debounce, cancellation, keyboard navigation and ARIA roles?
Drive the search from the control's valueChanges with debounceTime, distinctUntilChanged and switchMap, show results in a listbox, and keep the active option in a signal. For accessibility use role combobox on the input with aria-expanded, aria-controls and aria-activedescendant, support ArrowUp, ArrowDown, Enter and Escape, and announce the result count.
Full answer
A typeahead looks small but combines streams, state, and accessibility.
Data flow:
control.valueChanges emits as the user types.
debounceTime(250) waits for a pause, map(trim) and distinctUntilChanged() skip no-ops.
switchMap calls the search and cancels the previous call, so slow old responses cannot overwrite newer ones. Put catchError inside it so one failure does not end the stream. Return of([]) for terms shorter than two characters.
A loading flag can be set with tap before switchMap and cleared afterwards. The final stream becomes a signal with toSignal.
UI state in signals: open, activeIndex, and the results. A selection writes the chosen value into the control and closes the list.
ARIA pattern (WAI-ARIA combobox with listbox popup):
The input has role="combobox", aria-expanded, aria-controls="listbox-id", aria-autocomplete="list", and aria-activedescendant set to the id of the active option.
The list has role="listbox", and each option has role="option", a unique id, and aria-selected.
Focus stays in the input. The "active" option is a visual and ARIA state only.
Keys: ArrowDown and ArrowUp move the active option (wrap or stop, and open the list if closed), Enter selects, Escape closes, and Tab closes without selecting.
Announce results with a live region: "5 results available".
Edge cases: empty results ("No matches"), clicking an option must not blur the input before the click is handled (use mousedown or prevent default), the list closes on blur with a short delay, and typing must reset the active index.
For production use, Angular Material's autocomplete or the CDK listbox gives tested keyboard and ARIA behaviour. Building it yourself shows that you understand what they do.
Angular 20.3, strict template check passes, and a Karma test checks the arrow-key and Enter behaviour. The search function is a local fake with a 100 ms delay.
Key points
`valueChanges` with `debounceTime`, `distinctUntilChanged`, and `switchMap` (and an inner `catchError`).
State in signals: results, `open`, and `activeIndex`.
ARIA: combobox input, listbox, options, and `aria-activedescendant`. Focus stays in the input.
Keys: arrows, Enter, Escape. Announce the result count.
Common mistakes
Using `mergeMap`, so old slow responses overwrite new ones.
Moving real focus into options, which breaks typing.
Closing the list on blur before the click on an option is processed.
Follow-ups
How would you cache previous searches?
How would you highlight the matching part of each result?
Why use `aria-activedescendant` and not moving focus?
Tips
Walk through the stream first, then the ARIA pattern.
Name the click-versus-blur race. It shows hands-on experience.
Say when you would use Material's autocomplete instead.