From ab39e2d58256c7c4ff122af3013acc0814ef5d97 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 11:35:52 -0500 Subject: [PATCH 1/6] Add failing specs for an interview question bank, practice deck and lesson 13 --- .../lessons/interview-bank.spec.ts | 29 ++++++ .../lessons/interview-practice.spec.ts | 92 +++++++++++++++++++ .../lessons/lesson-13-interview.spec.ts | 49 ++++++++++ 3 files changed, 170 insertions(+) create mode 100644 src/app/thoughts-content/lessons/interview-bank.spec.ts create mode 100644 src/app/thoughts-content/lessons/interview-practice.spec.ts create mode 100644 src/app/thoughts-content/lessons/lesson-13-interview.spec.ts diff --git a/src/app/thoughts-content/lessons/interview-bank.spec.ts b/src/app/thoughts-content/lessons/interview-bank.spec.ts new file mode 100644 index 0000000..4e5b3de --- /dev/null +++ b/src/app/thoughts-content/lessons/interview-bank.spec.ts @@ -0,0 +1,29 @@ +import { TestBed } from '@angular/core/testing'; +import { INTERVIEW_BANK } from './interview-bank'; +import { LESSON_PAGES } from './lessons'; + +describe('INTERVIEW_BANK', () => { + it('has questions for exactly the lessons that exist', () => { + expect(Object.keys(INTERVIEW_BANK).sort()).toEqual(Object.keys(LESSON_PAGES).sort()); + }); + + it.each(Object.entries(INTERVIEW_BANK))('%s has at least five questions', (_slug, questions) => { + expect(questions.length).toBeGreaterThanOrEqual(5); + }); + + it('never repeats a question, since the practice deck and the lists track by its text', () => { + const all = Object.values(INTERVIEW_BANK).flatMap((questions) => questions.map(({ q }) => q)); + const repeated = all.filter((q, index) => all.indexOf(q) !== index); + expect(repeated).toEqual([]); + }); + + it.each(Object.keys(LESSON_PAGES))('%s renders its questions from the bank', async (slug) => { + const fixture = TestBed.createComponent(await LESSON_PAGES[slug]()); + await fixture.whenStable(); + + const summaries = [ + ...(fixture.nativeElement as HTMLElement).querySelectorAll('app-interview-questions summary'), + ].map((summary) => summary.textContent?.trim()); + expect(summaries).toEqual(INTERVIEW_BANK[slug].map(({ q }) => q)); + }); +}); diff --git a/src/app/thoughts-content/lessons/interview-practice.spec.ts b/src/app/thoughts-content/lessons/interview-practice.spec.ts new file mode 100644 index 0000000..ecef8cd --- /dev/null +++ b/src/app/thoughts-content/lessons/interview-practice.spec.ts @@ -0,0 +1,92 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import * as axeMatchers from 'vitest-axe/matchers'; +import { axe } from '../../../test/a11y'; +import { InterviewPractice, PracticeCard } from './interview-practice'; + +expect.extend(axeMatchers); + +const CARDS: PracticeCard[] = [ + { topic: 'Signals', q: 'What is a signal?', a: 'A reactive value.' }, + { topic: 'Signals', q: 'What is computed?', a: 'A derived signal.' }, + { topic: 'Routing', q: 'What is a guard?', a: 'A function that decides navigation.' }, +]; + +describe('InterviewPractice', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + const text = (selector: string) => el.querySelector(selector)?.textContent?.trim(); + const answer = () => el.querySelector('#practice-answer'); + const click = async (selector: string) => { + el.querySelector(selector)!.click(); + await fixture.whenStable(); + }; + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [InterviewPractice] }).compileComponents(); + fixture = TestBed.createComponent(InterviewPractice); + fixture.componentRef.setInput('cards', CARDS); + await fixture.whenStable(); + el = fixture.nativeElement as HTMLElement; + }); + + it('asks the first question with its answer hidden', () => { + expect(text('#practice-question')).toBe('What is a signal?'); + expect(text('#practice-topic')).toBe('Signals'); + expect(answer()?.hidden).toBe(true); + expect(text('#practice-progress')).toBe('3 left, 0 known'); + }); + + it('reveals the answer on demand, and says so to assistive tech', async () => { + await click('#practice-reveal'); + + expect(answer()?.hidden).toBe(false); + expect(text('#practice-answer')).toBe('A reactive value.'); + expect(el.querySelector('#practice-reveal')?.getAttribute('aria-expanded')).toBe('true'); + }); + + it('"Got it" takes the card out of the deck and hides the next answer', async () => { + await click('#practice-reveal'); + await click('#practice-known'); + + expect(text('#practice-question')).toBe('What is computed?'); + expect(answer()?.hidden).toBe(true); + expect(text('#practice-progress')).toBe('2 left, 1 known'); + }); + + it('"Ask again" sends the card to the back of the deck', async () => { + await click('#practice-again'); + expect(text('#practice-question')).toBe('What is computed?'); + expect(text('#practice-progress')).toBe('3 left, 0 known'); + + await click('#practice-known'); + await click('#practice-known'); + expect(text('#practice-question')).toBe('What is a signal?'); + }); + + it('says when the deck is done, and starts over', async () => { + for (let i = 0; i < CARDS.length; i++) await click('#practice-known'); + + expect(text('#practice-progress')).toBe('0 left, 3 known'); + expect(el.querySelector('#practice-question')).toBeNull(); + await click('#practice-restart'); + + expect(text('#practice-question')).toBe('What is a signal?'); + expect(text('#practice-progress')).toBe('3 left, 0 known'); + }); + + it('narrows the deck to one topic', async () => { + const select = el.querySelector('#practice-filter')!; + select.value = 'Routing'; + select.dispatchEvent(new Event('change')); + await fixture.whenStable(); + + expect(text('#practice-question')).toBe('What is a guard?'); + expect(text('#practice-progress')).toBe('1 left, 0 known'); + }); + + it('has no axe violations with an answer showing', async () => { + await click('#practice-reveal'); + expect(await axe(el)).toHaveNoViolations(); + }); +}); diff --git a/src/app/thoughts-content/lessons/lesson-13-interview.spec.ts b/src/app/thoughts-content/lessons/lesson-13-interview.spec.ts new file mode 100644 index 0000000..cfac03a --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-13-interview.spec.ts @@ -0,0 +1,49 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import * as axeMatchers from 'vitest-axe/matchers'; +import { axe } from '../../../test/a11y'; +import { INTERVIEW_BANK } from './interview-bank'; +import { LESSON_PAGES } from './lessons'; +import { Lesson13Interview } from './lesson-13-interview'; + +expect.extend(axeMatchers); + +describe('Lesson13Interview', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [Lesson13Interview] }).compileComponents(); + fixture = TestBed.createComponent(Lesson13Interview); + await fixture.whenStable(); + el = fixture.nativeElement as HTMLElement; + }); + + it('is registered as the lesson page for its thought', () => { + expect(LESSON_PAGES['angular-13-interview']).toBeDefined(); + }); + + it('teaches at three levels, then pitfalls, practice and interview questions', () => { + const headings = [...el.querySelectorAll('h2')].map((h) => h.textContent?.trim()); + expect(headings).toEqual( + expect.arrayContaining([ + 'Simple', + 'Intermediate', + 'Expert', + 'Pitfalls', + 'Practice', + 'Interview questions', + ]), + ); + }); + + it('practises every question in the guide, starting with lesson 01', () => { + const total = Object.values(INTERVIEW_BANK).flat().length; + + expect(el.querySelector('#practice-progress')?.textContent?.trim()).toBe(`${total} left, 0 known`); + expect(el.querySelector('#practice-topic')?.textContent?.trim()).toBe('Project structure'); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); From a597659e97d655db950451890b71b6fde8d63139 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 11:36:50 -0500 Subject: [PATCH 2/6] Move every lesson's interview questions into one bank --- .../lessons/interview-bank.ts | 320 ++++++++++++++++++ .../lessons/lesson-01-structure.ts | 24 +- .../lessons/lesson-02-components.ts | 28 +- .../lessons/lesson-03-templates.ts | 28 +- .../lessons/lesson-04-signals.ts | 28 +- .../thoughts-content/lessons/lesson-05-di.ts | 28 +- .../lessons/lesson-06-rxjs.ts | 28 +- .../lessons/lesson-07-routing.ts | 28 +- .../lessons/lesson-08-forms.ts | 28 +- .../lessons/lesson-09-change-detection.ts | 28 +- .../lessons/lesson-10-directives.ts | 28 +- .../lessons/lesson-11-testing.ts | 28 +- .../thoughts-content/lessons/lesson-12-ssr.ts | 28 +- 13 files changed, 344 insertions(+), 308 deletions(-) create mode 100644 src/app/thoughts-content/lessons/interview-bank.ts diff --git a/src/app/thoughts-content/lessons/interview-bank.ts b/src/app/thoughts-content/lessons/interview-bank.ts new file mode 100644 index 0000000..c8e7ebb --- /dev/null +++ b/src/app/thoughts-content/lessons/interview-bank.ts @@ -0,0 +1,320 @@ +import type { InterviewQuestion } from './interview-questions'; + +/** + * Every lesson's interview questions, keyed by the lesson's slug. + * + * They used to live inside each lesson component. Lesson 13's practice deck + * needs all of them, and importing every lesson component to get at its + * questions would pull all twelve pages into one chunk, so the data lives here + * and each lesson reads its own entry. + */ +export const INTERVIEW_BANK: Record = { + 'angular-01-project-structure': [ + { + q: 'How would you structure a large Angular app?', + a: 'By feature, with three layers: a thin shell, shared building blocks, and lazy-loaded feature folders. Dependencies point one way: features and shell depend on shared, never on each other. I enforce that with a lint rule or a fitness test, because a convention nobody checks decays.', + }, + { + q: 'What replaced AppModule?', + a: 'bootstrapApplication(RootComponent, appConfig). appConfig holds the providers an AppModule used to import, as provideRouter, provideHttpClient and so on. Components declare their own dependencies in imports: [] instead of a module doing it for them.', + }, + { + q: "What's the difference between providers in app.config.ts and in a route?", + a: "app.config.ts providers live in the root environment injector: one instance for the whole app. A route's providers array creates a child environment injector, so the service exists only for that route subtree and can be lazy loaded with it.", + }, + { + q: 'Why are barrel files risky in Angular?', + a: 'They hide the real dependency graph. Circular imports appear easily, and importing one symbol from a barrel can drag in the whole folder, including a feature you meant to lazy load, which defeats code splitting.', + }, + { + q: 'Which tsconfig and compiler flags would you insist on?', + a: 'strict for TypeScript, and strictTemplates in angularCompilerOptions so bindings are type-checked in templates. Turning them off hides real bugs, such as passing a possibly-undefined value to an input.', + }, + ], + 'angular-02-components': [ + { + q: 'What makes a component standalone, and why did Angular move to it?', + a: 'It declares its own dependencies in imports: [] instead of belonging to an NgModule. The dependency graph is explicit per component, lazy loading works at component granularity, and there is one fewer concept to learn. Standalone has been the default since v19.', + }, + { + q: 'input() vs @Input()?', + a: 'input() returns a read-only signal, so you derive from it with computed() and there is no need for ngOnChanges. It supports required inputs and transforms, and the compiler type-checks it. @Input() is a decorated mutable field and still everywhere in older code.', + }, + { + q: 'How does two-way binding work?', + a: 'It is sugar. [(x)]="v" expands to [x]="v" (xChange)="v = $event". model() declares both halves at once. With a signal you pass the signal itself, [(count)]="count", and Angular writes to it.', + }, + { + q: 'What is content projection and when would you use multi-slot?', + a: 'Passing markup from parent into a child through . Multi-slot uses select with a CSS selector to route parts, for example a card with header, body and footer slots. The parent still owns the projected content: it is created and change-detected as part of the parent.', + }, + { + q: 'How do you create a component dynamically?', + a: 'Declaratively with NgComponentOutlet (inputs via ngComponentOutletInputs), or imperatively with ViewContainerRef.createComponent(). Combine either with a dynamic import() so the component is its own lazy chunk. This site loads every lesson page that way.', + }, + { + q: 'What are the view encapsulation modes?', + a: 'Emulated (default) rewrites selectors with generated attributes so styles stay scoped. None makes them global. ShadowDom uses native shadow roots. Use None sparingly and scope selectors by hand. ::ng-deep is deprecated.', + }, + ], + 'angular-03-templates': [ + { + q: "What's the difference between property binding and attribute binding?", + a: '[x] sets the DOM property, the live value. [attr.x] sets the HTML attribute, the initial value. They diverge for things like an input value after typing. Use attr only when there is no property, such as aria-*, colspan or SVG attributes.', + }, + { + q: 'Why does @for require track, and what should you track by?', + a: 'track lets Angular map items to DOM rows across changes, so it can move or keep rows instead of recreating them. Track a stable unique id. $index is only safe for static lists that never reorder or delete.', + }, + { + q: 'Pure vs impure pipes?', + a: 'A pure pipe re-runs only when its input reference changes, so it is effectively memoised per binding. An impure pipe runs on every change detection pass. Most custom pipes should be pure. AsyncPipe is the classic impure one, because it has to check for new emissions.', + }, + { + q: 'Built-in control flow vs *ngIf / *ngFor?', + a: "@if, @for and @switch are part of the template language. They need no imports, @if narrows types, @for makes tracking mandatory and has @empty, and they're faster. The structural directives desugar to ng-template plus a directive and are still common in older code. There's an automatic migration: ng generate @angular/core:control-flow.", + }, + { + q: 'How do you listen to a global event like keydown on document?', + a: "host: { '(document:keydown)': 'onKey($event)' } in the component metadata, or @HostListener in older code. Both clean themselves up when the component is destroyed. Never add a raw addEventListener without removing it in DestroyRef.", + }, + { + q: 'How does Angular protect against XSS in templates?', + a: 'Interpolation is always text-escaped, and values bound into innerHTML, URLs and styles are sanitized by context. bypassSecurityTrust* disables that for one value, so it should only ever see trusted input.', + }, + ], + 'angular-04-signals': [ + { + q: 'What problem do signals solve compared to Zone.js change detection?', + a: 'Zone.js patched every async API and re-checked the whole component tree after any event, because Angular could not know what changed. Signals record exactly which views read which values, so Angular can refresh only what depends on a change. That enables zoneless apps: smaller bundles, cleaner stack traces, less wasted work.', + }, + { + q: 'signal vs computed vs effect vs linkedSignal?', + a: 'signal holds writable state. computed derives read-only state, lazily and memoised. linkedSignal derives state that can also be written locally and resets when its source changes. effect runs side effects outside the signal graph, such as the DOM, storage or logging, and should not be used to sync signals.', + }, + { + q: 'Why does updating an array inside a signal sometimes not re-render?', + a: 'Signals use Object.is equality by default. Mutating the existing array keeps the same reference, so nothing is notified. Replace it instead, with update(list => [...list, item]), or supply a custom equal function if you really need one.', + }, + { + q: 'When would you still use RxJS?', + a: 'For events over time: debouncing input, cancelling in-flight requests with switchMap, websockets, retries and polling. Signals are for current state. toSignal and toObservable bridge the two at the edges.', + }, + { + q: 'How do you expose state from a service safely?', + a: 'Keep writable signals private and expose asReadonly() views plus methods that encode the allowed transitions. Consumers then get reactivity without being able to bypass the rules. Components get computed() views where they need derived data.', + }, + { + q: 'What is resource() and when is it better than subscribing?', + a: 'A signal-based async primitive. You give it reactive params and a loader, and it exposes value, status, error and isLoading as signals. It cancels stale loads when params change and registers as a pending task, so SSR waits for it. It replaces the subscribe-and-set-loading-flags boilerplate in most read-only data fetching.', + }, + ], + 'angular-05-dependency-injection': [ + { + q: 'What is dependency injection, and why does Angular use it?', + a: 'A class declares what it needs and the framework supplies it, instead of the class constructing its own dependencies. That decouples code from concrete implementations, so you can swap them per environment (browser vs server) or per test, and it lets Angular control lifetimes: one app-wide instance, or one per component subtree.', + }, + { + q: "What does providedIn: 'root' do, and how is it different from listing a service in providers?", + a: "providedIn: 'root' registers the service with the root environment injector: one instance for the app, created lazily, and dropped from the bundle if nothing injects it. Listing it in a component's providers creates a new instance for that component and its children. Doing both gives you two instances, a classic source of state that silently stops syncing.", + }, + { + q: 'When do you need an InjectionToken?', + a: 'When the thing you inject is not a class: an interface, a config object, a string or a browser global. Interfaces are erased at runtime, so they cannot be lookup keys. In this project BROWSER_STORAGE is a token for Storage, with a factory that returns localStorage in the browser and null on the server.', + }, + { + q: 'How does Angular resolve a dependency?', + a: 'It walks the element injector tree first, starting at the requesting element and going up through ancestor components. Then it walks the environment injectors: lazy route injectors, root, then platform. The first provider found wins. If none is found it throws NG0201, unless the request was optional. Modifiers like self, skipSelf and host change where the walk starts or stops.', + }, + { + q: 'inject() or constructor injection?', + a: 'They resolve the same way. inject() is the modern default: it works in field initialisers and functions (guards, interceptors, factories), plays well with inheritance because subclasses do not have to pass dependencies to super(), and does not depend on TypeScript decorator metadata. It must be called in an injection context.', + }, + { + q: 'How do you test a service that touches localStorage or the network?', + a: 'Put the dependency behind DI and override it in TestBed. Use { provide: TOKEN, useValue: fake } for a token, or provideHttpClientTesting() for HttpClient. The service code never changes between tests and production, and the tests never touch real global state.', + }, + ], + 'angular-06-rxjs': [ + { + q: 'switchMap, mergeMap, concatMap, exhaustMap: when do you use each?', + a: 'All four map a value to an inner Observable. switchMap cancels the previous inner stream, so use it when only the latest matters: search, route params. mergeMap runs them in parallel, for independent work. concatMap queues them in order, for writes that must not interleave. exhaustMap ignores new values while one is running, for a submit button double-click or a login request.', + }, + { + q: 'What is the difference between a hot and a cold Observable?', + a: 'A cold Observable starts its work separately for each subscriber: every subscribe to an HttpClient call sends a request. A hot one shares a single source that runs regardless, like DOM events or a Subject. You make a cold one shared with share() or shareReplay().', + }, + { + q: 'How do you avoid memory leaks with subscriptions in Angular?', + a: "Mostly by not subscribing manually: toSignal() and the async pipe unsubscribe when the component is destroyed. For a manual subscribe, use takeUntilDestroyed(), which takes a DestroyRef from the injection context. Streams that complete on their own, like a single HTTP call, don't leak, but they aren't cancelled either unless you unsubscribe.", + }, + { + q: 'Subject, BehaviorSubject, ReplaySubject?', + a: 'A Subject is both an Observable and an Observer: you push values in with next() and subscribers get them from then on. BehaviorSubject requires an initial value and gives new subscribers the current one immediately, which made it the service-store pattern before signals. ReplaySubject replays the last N values to late subscribers.', + }, + { + q: 'What is an HTTP interceptor, and what have you used one for?', + a: 'A function in the HttpClient pipeline that sees every request and its response Observable. Typical uses: adding auth headers, retrying, logging, turning errors into user messages, and caching. On my site one retries GETs that fail with a network error or 5xx, with exponential backoff, and never retries POSTs, because those are not safe to repeat.', + }, + { + q: 'Signals or RxJS?', + a: 'Both, at different jobs. Signals hold state that the UI reads synchronously. RxJS models events over time: debouncing, cancellation, retries, combining streams. A common shape is signal input, then toObservable, then the operators, then toSignal back out for the template.', + }, + ], + 'angular-07-routing': [ + { + q: 'How does the router decide which route matches?', + a: 'It walks the route array in order and takes the first route whose path fits, depth-first through children. So specific routes go before general ones, and the ** wildcard goes last. An empty-path redirect needs pathMatch: full, or it matches every URL by prefix.', + }, + { + q: 'How do you read route parameters in a component?', + a: 'Today, with withComponentInputBinding() enabled, declare an input with the param name and the router sets it, including on reuse. Without it, inject ActivatedRoute and use paramMap, an Observable, or toSignal(paramMap). Avoid route.snapshot in components the router may reuse, because it never updates.', + }, + { + q: 'What are guards and resolvers?', + a: 'Guards are functions that run during navigation. canActivate decides entry, canMatch decides whether a route is considered at all (good for feature flags and lazy loading), canDeactivate guards leaving, for example with unsaved changes. They can return a UrlTree to redirect. Resolvers fetch data before activation. Many apps now load in the component with resource() instead, so the page can render a loading state rather than blocking navigation.', + }, + { + q: 'How does lazy loading work with standalone components?', + a: 'loadComponent takes a function returning a dynamic import of a component, and loadChildren returns a routes array. The bundler splits each into its own chunk, fetched on first navigation. Preloading strategies, such as PreloadAllModules or a custom one, can fetch chunks in the background after startup.', + }, + { + q: 'Path params or query params?', + a: 'Path params identify the resource: /thoughts/:slug. Query params carry optional view state: sorting, filters, paging. With SSR or prerendering, anything that should be its own page with its own HTML and canonical URL needs to be in the path. On my site that is why tag pages are /thoughts/tag/:tag.', + }, + { + q: 'How do you test routing?', + a: 'With RouterTestingHarness: configure provideRouter with real routes, navigate by URL, and assert on the rendered component and router.url. It catches what mocked ActivatedRoute specs miss, such as component reuse on a param change. In my project a spec runs the real route table with the real app config, so a missing wildcard or router feature fails a test.', + }, + ], + 'angular-08-forms': [ + { + q: 'Reactive or template-driven forms?', + a: 'Template-driven forms build the model from ngModel in the template: quick for simple cases, but the logic is spread through HTML and hard to unit test. Reactive forms define the model in TypeScript, which makes them strongly typed, testable without a DOM, and better for dynamic fields, cross-field validation and complex flows. I default to reactive. In Angular 21, Signal Forms are an experimental third option built on signals.', + }, + { + q: 'How do you write a custom validator, and a cross-field one?', + a: 'A ValidatorFn takes a control and returns null when valid or an errors object like { blank: true }. For rules involving several fields, such as password confirmation or a date range, put the validator on the FormGroup so it sees every value and re-runs when any of them changes. Read it with group.hasError().', + }, + { + q: 'What does a ControlValueAccessor do?', + a: 'It is the bridge between a form control and a component or element. writeValue pushes the model into the view, registerOnChange and registerOnTouched give the component callbacks to report changes back, and setDisabledState handles disabling. Provide it with NG_VALUE_ACCESSOR as a multi provider, and formControlName and ngModel work on your component.', + }, + { + q: 'How do async validators work?', + a: 'They return an Observable or Promise of errors or null, and run only after the sync validators pass. While they run, the control status is PENDING. To avoid a request per keystroke, use updateOn: blur or debounce inside the validator with timer() and switchMap, since the validator is resubscribed on each value change.', + }, + { + q: 'How do you make a form accessible?', + a: 'Every input has a real label. Errors show once the field is touched, and are linked with aria-invalid and aria-describedby. The submit button stays enabled, and an invalid submit marks everything touched and focuses the first invalid field. Results go into a live region that already exists in the DOM. Use autocomplete attributes for personal data.', + }, + { + q: 'What changed with typed forms?', + a: 'Since Angular 14, FormControl, FormGroup and FormArray are generic and infer their types from initial values, so form.value.email is typed and typos are compile errors. nonNullable controls reset to their initial value instead of null, which removes string | null everywhere. UntypedFormGroup exists for migrating old code.', + }, + ], + 'angular-09-change-detection': [ + { + q: 'How does change detection work in Angular?', + a: 'Angular walks the component tree and re-evaluates template bindings, patching the DOM where values changed. With Zone.js, a pass ran after any async event because Angular could not know what changed. In a zoneless app, a pass is scheduled by signal changes, template events, markForCheck or setInput. OnPush and signals then narrow which components are actually checked.', + }, + { + q: 'When is an OnPush component checked?', + a: 'When one of its inputs receives a new reference, when an event fires in its template or a child, when a signal read in its template changes, or when markForCheck is called on it or a descendant (the async pipe does that). Mutating an object input in place triggers none of these.', + }, + { + q: 'What causes ExpressionChangedAfterItHasBeenChecked, and how do you fix it?', + a: 'In development mode Angular runs a second verification pass and throws if a binding changed after it was checked. That means state was changed during change detection itself: in ngAfterViewInit, by a child updating a parent, or by a getter returning a new object each time. Fix the data flow, for example by deriving the value with computed or setting it earlier. Wrapping it in setTimeout hides the bug and costs an extra render.', + }, + { + q: 'markForCheck vs detectChanges?', + a: 'markForCheck marks the view and its ancestors dirty so the next scheduled pass checks them. It is cheap and the usual choice. detectChanges synchronously runs change detection on that view and its children immediately, which is useful in tests or for detached views but easy to overuse.', + }, + { + q: 'How do signals change the picture?', + a: 'A signal knows exactly which views read it, so a change marks only those views for refresh, and Angular can skip OnPush ancestors. That is what makes zoneless practical: no global check after every event, and OnPush costs almost nothing to adopt when state is in signals.', + }, + { + q: 'How would you move a large app to OnPush?', + a: 'Component by component, leaves first, since they have the fewest dependencies. Look for plain fields mutated asynchronously, inputs mutated in place, and tests that rely on detectChanges after setting a field. Convert that state to signals or immutable updates. Then enforce it with the ESLint rule or a fitness test so new components start as OnPush. I did exactly that on my site and enforced it with a spec.', + }, + ], + 'angular-10-directives': [ + { + q: 'What kinds of directives are there?', + a: 'Components, which are directives with a template; attribute directives, which change the appearance or behaviour of their host element; and structural directives, which add or remove DOM by rendering a TemplateRef into a ViewContainerRef. Since Angular 17 the built-in @if, @for and @switch blocks cover most structural needs without a directive.', + }, + { + q: 'What does the * in *ngIf do?', + a: 'It is shorthand. The element is wrapped in an , and the expression is bound to an input named after the directive selector. Microsyntax like "let item of items; trackBy: f" maps to more inputs, such as ngForOf and ngForTrackBy, and to template context variables.', + }, + { + q: 'What are host directives and why use them?', + a: 'hostDirectives on a component or directive applies other standalone directives to its host element, as if their attributes were written there. You pick which inputs and outputs to expose and can alias them. It is composition instead of inheritance: behaviour like focus handling, tooltips or scroll tracking can be shared without base classes, and consumers cannot forget to add it.', + }, + { + q: 'How do parent and child directives communicate?', + a: 'Through DI. A child injects the parent directive, optionally, from its element injector and registers itself, the way NgModel registers with NgForm or my headings register with ScrollSpy. The parent can also use contentChildren to query children. Registration keeps the parent generic, and queries are good when the parent needs an ordered list of children to render.', + }, + { + q: '@HostBinding and @HostListener vs the host property?', + a: 'Both do the same job. The Angular style guide now prefers the host property in the decorator metadata, because all host bindings sit in one place and work cleanly with signals. The decorators still work, and plenty of existing code uses them.', + }, + { + q: 'Where should DOM work in a directive happen?', + a: 'Not in the constructor, because children do not exist yet and on the server there is no browser DOM. Use afterNextRender or afterEveryRender for browser-only work like measuring or observers, and DestroyRef to clean up. Bindings in the host metadata are the safe way to write to the host element, since Angular applies them on the server too.', + }, + ], + 'angular-11-testing': [ + { + q: 'What do you test in an Angular component?', + a: 'Its behaviour through its public surface: what renders for given inputs, what happens on clicks and typing, which outputs it emits, and what it asks its services to do. Not private methods or internal fields, because those tests break on refactors that change nothing a user can see. I also run axe in component specs so accessibility regressions fail like any other bug.', + }, + { + q: 'How do you test a component that makes HTTP calls?', + a: 'Provide provideHttpClient() and provideHttpClientTesting(), then inject HttpTestingController. Trigger the behaviour, use expectOne to assert the request, flush a response or an error, and assert on the rendered result. verify() in afterEach fails the test if any request was left unanswered. For retries and debouncing, add fake timers so the test controls time.', + }, + { + q: 'Unit, integration or e2e?', + a: 'Mostly fast unit and component tests, because they pin behaviour cheaply and run on every save. Integration-style specs use the real config, for example routing tested against appConfig. A few e2e tests cover what needs a real browser: layout, scrolling, IntersectionObserver, and the critical user journeys. E2e tests are slow and more prone to flakiness, so each one should earn its place.', + }, + { + q: 'How do you test RxJS code?', + a: 'With marble tests on the RxJS TestScheduler. Inside scheduler.run(), every timer uses virtual time, so delays, debounces and races are deterministic and instant. You describe input streams as marble strings and assert the output against an expected one. For simple cases, subscribing and asserting after fake timers is fine too.', + }, + { + q: 'Karma and Jasmine vs Jest vs Vitest?', + a: 'Karma with Jasmine was the Angular default for years and ran tests in a real browser. New Angular 21 projects default to Vitest through the @angular/build:unit-test builder, which runs in jsdom with an optional browser mode. Jest was a common community choice in between. The TestBed API is the same in all of them, so most specs move between runners with little change.', + }, + { + q: 'Tell me about a test that caught something.', + a: 'On my site, a fitness test that reads the CI workflow showed that its typecheck step checked zero files. The root tsconfig only has project references, so plain tsc compiles nothing. CI had been green the whole time. The spec now requires the real tsconfigs, a production build, and a timeout on every job.', + }, + ], + 'angular-12-ssr': [ + { + q: 'What is the difference between CSR, SSR and SSG?', + a: 'CSR renders in the browser: fast to serve, but nothing shows until the JavaScript runs, and crawlers see an empty shell. SSR renders on the server per request, so the HTML is complete and can depend on the request, at the cost of server time. SSG, or prerendering, renders once at build time and serves static files, which is the cheapest and fastest when content only changes on deploy. Angular 21 chooses per route with RenderMode.Client, Server and Prerender in the server routes.', + }, + { + q: 'What is hydration, and what breaks it?', + a: "Hydration is the browser adopting the server's DOM instead of re-creating it, so there's no flicker or lost scroll position. It needs the first client render to match the server's. It breaks when the two renders differ, for example a time, a random value or a locale, or when code changes the DOM outside Angular. Angular reports NG0500 for structural mismatches. ngSkipHydration opts a subtree out, but that's a workaround, not a fix.", + }, + { + q: 'How do you run code that needs the browser?', + a: 'afterNextRender for one-time setup and afterEveryRender for work after every render. Both only run in the browser, after the DOM exists. Inject DOCUMENT rather than touching the global, and provide browser APIs like localStorage through a token with a server fallback. isPlatformBrowser still exists, but render hooks are usually the better fit.', + }, + { + q: 'How do you avoid fetching data twice with SSR?', + a: "With hydration on, HttpClient's transfer cache stores GET and HEAD responses made on the server in TransferState, and the browser reuses them during hydration. For data that doesn't come through HttpClient, write it to TransferState yourself with makeStateKey on the server and read it in the browser.", + }, + { + q: 'What is incremental hydration?', + a: 'A @defer block with a hydrate trigger, such as hydrate on viewport, interaction or idle, renders fully on the server but stays dehydrated in the browser until the trigger fires, and its code is only downloaded then. Users see the content immediately while less JavaScript runs on load. hydrate never keeps static content static. It needs withIncrementalHydration() in provideClientHydration.', + }, + { + q: 'Tell me about an SSR bug you fixed.', + a: 'My site prerenders its blog pages, and every one of them shipped the menu bar clock as it was at build time. The bar was also marked ngSkipHydration, so the browser threw the server DOM away and rebuilt it. I made the clock render empty on the server, started it in afterNextRender, and removed ngSkipHydration so the bar hydrates. A spec renders the bar through the real server platform and asserts both.', + }, + ], +}; diff --git a/src/app/thoughts-content/lessons/lesson-01-structure.ts b/src/app/thoughts-content/lessons/lesson-01-structure.ts index b65c561..658691a 100644 --- a/src/app/thoughts-content/lessons/lesson-01-structure.ts +++ b/src/app/thoughts-content/lessons/lesson-01-structure.ts @@ -1,5 +1,6 @@ import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core'; import { CodeBlock } from './code-block'; +import { INTERVIEW_BANK } from './interview-bank'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; import { LessonSection } from './lesson-section'; @@ -241,26 +242,5 @@ apps/ one folder per desktop app, lazy loaded });`, }; - protected readonly interview = [ - { - q: 'How would you structure a large Angular app?', - a: 'By feature, with three layers: a thin shell, shared building blocks, and lazy-loaded feature folders. Dependencies point one way: features and shell depend on shared, never on each other. I enforce that with a lint rule or a fitness test, because a convention nobody checks decays.', - }, - { - q: 'What replaced AppModule?', - a: 'bootstrapApplication(RootComponent, appConfig). appConfig holds the providers an AppModule used to import, as provideRouter, provideHttpClient and so on. Components declare their own dependencies in imports: [] instead of a module doing it for them.', - }, - { - q: "What's the difference between providers in app.config.ts and in a route?", - a: "app.config.ts providers live in the root environment injector: one instance for the whole app. A route's providers array creates a child environment injector, so the service exists only for that route subtree and can be lazy loaded with it.", - }, - { - q: 'Why are barrel files risky in Angular?', - a: 'They hide the real dependency graph. Circular imports appear easily, and importing one symbol from a barrel can drag in the whole folder, including a feature you meant to lazy load, which defeats code splitting.', - }, - { - q: 'Which tsconfig and compiler flags would you insist on?', - a: 'strict for TypeScript, and strictTemplates in angularCompilerOptions so bindings are type-checked in templates. Turning them off hides real bugs, such as passing a possibly-undefined value to an input.', - }, - ]; + protected readonly interview = INTERVIEW_BANK['angular-01-project-structure']; } diff --git a/src/app/thoughts-content/lessons/lesson-02-components.ts b/src/app/thoughts-content/lessons/lesson-02-components.ts index 1b1a21c..1da1cdc 100644 --- a/src/app/thoughts-content/lessons/lesson-02-components.ts +++ b/src/app/thoughts-content/lessons/lesson-02-components.ts @@ -1,6 +1,7 @@ import { ChangeDetectionStrategy, Component, input, model, output, signal } from '@angular/core'; import { Callout } from './callout'; import { CodeBlock } from './code-block'; +import { INTERVIEW_BANK } from './interview-bank'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; import { LessonSection } from './lesson-section'; @@ -259,30 +260,5 @@ export class Callout { }`, }; - protected readonly interview = [ - { - q: 'What makes a component standalone, and why did Angular move to it?', - a: 'It declares its own dependencies in imports: [] instead of belonging to an NgModule. The dependency graph is explicit per component, lazy loading works at component granularity, and there is one fewer concept to learn. Standalone has been the default since v19.', - }, - { - q: 'input() vs @Input()?', - a: 'input() returns a read-only signal, so you derive from it with computed() and there is no need for ngOnChanges. It supports required inputs and transforms, and the compiler type-checks it. @Input() is a decorated mutable field and still everywhere in older code.', - }, - { - q: 'How does two-way binding work?', - a: 'It is sugar. [(x)]="v" expands to [x]="v" (xChange)="v = $event". model() declares both halves at once. With a signal you pass the signal itself, [(count)]="count", and Angular writes to it.', - }, - { - q: 'What is content projection and when would you use multi-slot?', - a: 'Passing markup from parent into a child through . Multi-slot uses select with a CSS selector to route parts, for example a card with header, body and footer slots. The parent still owns the projected content: it is created and change-detected as part of the parent.', - }, - { - q: 'How do you create a component dynamically?', - a: 'Declaratively with NgComponentOutlet (inputs via ngComponentOutletInputs), or imperatively with ViewContainerRef.createComponent(). Combine either with a dynamic import() so the component is its own lazy chunk. This site loads every lesson page that way.', - }, - { - q: 'What are the view encapsulation modes?', - a: 'Emulated (default) rewrites selectors with generated attributes so styles stay scoped. None makes them global. ShadowDom uses native shadow roots. Use None sparingly and scope selectors by hand. ::ng-deep is deprecated.', - }, - ]; + protected readonly interview = INTERVIEW_BANK['angular-02-components']; } diff --git a/src/app/thoughts-content/lessons/lesson-03-templates.ts b/src/app/thoughts-content/lessons/lesson-03-templates.ts index f34954f..aac084a 100644 --- a/src/app/thoughts-content/lessons/lesson-03-templates.ts +++ b/src/app/thoughts-content/lessons/lesson-03-templates.ts @@ -1,6 +1,7 @@ import { ChangeDetectionStrategy, Component, signal } from '@angular/core'; import { Callout } from './callout'; import { CodeBlock } from './code-block'; +import { INTERVIEW_BANK } from './interview-bank'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; import { LessonSection } from './lesson-section'; @@ -253,30 +254,5 @@ onKeydown(event: KeyboardEvent): void { }`, }; - protected readonly interview = [ - { - q: "What's the difference between property binding and attribute binding?", - a: '[x] sets the DOM property, the live value. [attr.x] sets the HTML attribute, the initial value. They diverge for things like an input value after typing. Use attr only when there is no property, such as aria-*, colspan or SVG attributes.', - }, - { - q: 'Why does @for require track, and what should you track by?', - a: 'track lets Angular map items to DOM rows across changes, so it can move or keep rows instead of recreating them. Track a stable unique id. $index is only safe for static lists that never reorder or delete.', - }, - { - q: 'Pure vs impure pipes?', - a: "A pure pipe re-runs only when its input reference changes, so it is effectively memoised per binding. An impure pipe runs on every change detection pass. Most custom pipes should be pure. AsyncPipe is the classic impure one, because it has to check for new emissions.", - }, - { - q: 'Built-in control flow vs *ngIf / *ngFor?', - a: "@if, @for and @switch are part of the template language. They need no imports, @if narrows types, @for makes tracking mandatory and has @empty, and they're faster. The structural directives desugar to ng-template plus a directive and are still common in older code. There's an automatic migration: ng generate @angular/core:control-flow.", - }, - { - q: 'How do you listen to a global event like keydown on document?', - a: "host: { '(document:keydown)': 'onKey($event)' } in the component metadata, or @HostListener in older code. Both clean themselves up when the component is destroyed. Never add a raw addEventListener without removing it in DestroyRef.", - }, - { - q: 'How does Angular protect against XSS in templates?', - a: 'Interpolation is always text-escaped, and values bound into innerHTML, URLs and styles are sanitized by context. bypassSecurityTrust* disables that for one value, so it should only ever see trusted input.', - }, - ]; + protected readonly interview = INTERVIEW_BANK['angular-03-templates']; } diff --git a/src/app/thoughts-content/lessons/lesson-04-signals.ts b/src/app/thoughts-content/lessons/lesson-04-signals.ts index ca0c2d6..35d4832 100644 --- a/src/app/thoughts-content/lessons/lesson-04-signals.ts +++ b/src/app/thoughts-content/lessons/lesson-04-signals.ts @@ -1,6 +1,7 @@ import { ChangeDetectionStrategy, Component, computed, effect, linkedSignal, signal, untracked } from '@angular/core'; import { Callout } from './callout'; import { CodeBlock } from './code-block'; +import { INTERVIEW_BANK } from './interview-bank'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; import { LessonSection } from './lesson-section'; @@ -245,30 +246,5 @@ readonly lessonPage = resource({ });`, }; - protected readonly interview = [ - { - q: 'What problem do signals solve compared to Zone.js change detection?', - a: 'Zone.js patched every async API and re-checked the whole component tree after any event, because Angular could not know what changed. Signals record exactly which views read which values, so Angular can refresh only what depends on a change. That enables zoneless apps: smaller bundles, cleaner stack traces, less wasted work.', - }, - { - q: 'signal vs computed vs effect vs linkedSignal?', - a: 'signal holds writable state. computed derives read-only state, lazily and memoised. linkedSignal derives state that can also be written locally and resets when its source changes. effect runs side effects outside the signal graph, such as the DOM, storage or logging, and should not be used to sync signals.', - }, - { - q: 'Why does updating an array inside a signal sometimes not re-render?', - a: 'Signals use Object.is equality by default. Mutating the existing array keeps the same reference, so nothing is notified. Replace it instead, with update(list => [...list, item]), or supply a custom equal function if you really need one.', - }, - { - q: 'When would you still use RxJS?', - a: 'For events over time: debouncing input, cancelling in-flight requests with switchMap, websockets, retries and polling. Signals are for current state. toSignal and toObservable bridge the two at the edges.', - }, - { - q: 'How do you expose state from a service safely?', - a: 'Keep writable signals private and expose asReadonly() views plus methods that encode the allowed transitions. Consumers then get reactivity without being able to bypass the rules. Components get computed() views where they need derived data.', - }, - { - q: 'What is resource() and when is it better than subscribing?', - a: 'A signal-based async primitive. You give it reactive params and a loader, and it exposes value, status, error and isLoading as signals. It cancels stale loads when params change and registers as a pending task, so SSR waits for it. It replaces the subscribe-and-set-loading-flags boilerplate in most read-only data fetching.', - }, - ]; + protected readonly interview = INTERVIEW_BANK['angular-04-signals']; } diff --git a/src/app/thoughts-content/lessons/lesson-05-di.ts b/src/app/thoughts-content/lessons/lesson-05-di.ts index 1a3ce84..bf439ad 100644 --- a/src/app/thoughts-content/lessons/lesson-05-di.ts +++ b/src/app/thoughts-content/lessons/lesson-05-di.ts @@ -1,6 +1,7 @@ import { ChangeDetectionStrategy, Component, inject, Injectable, input, signal } from '@angular/core'; import { Callout } from './callout'; import { CodeBlock } from './code-block'; +import { INTERVIEW_BANK } from './interview-bank'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; import { LessonSection } from './lesson-section'; @@ -273,30 +274,5 @@ private readonly analytics = inject(Analytics, { optional: true }); private readonly parentMenu = inject(Menu, { skipSelf: true, optional: true });`, }; - protected readonly interview = [ - { - q: 'What is dependency injection, and why does Angular use it?', - a: 'A class declares what it needs and the framework supplies it, instead of the class constructing its own dependencies. That decouples code from concrete implementations, so you can swap them per environment (browser vs server) or per test, and it lets Angular control lifetimes: one app-wide instance, or one per component subtree.', - }, - { - q: "What does providedIn: 'root' do, and how is it different from listing a service in providers?", - a: "providedIn: 'root' registers the service with the root environment injector: one instance for the app, created lazily, and dropped from the bundle if nothing injects it. Listing it in a component's providers creates a new instance for that component and its children. Doing both gives you two instances, a classic source of state that silently stops syncing.", - }, - { - q: 'When do you need an InjectionToken?', - a: 'When the thing you inject is not a class: an interface, a config object, a string or a browser global. Interfaces are erased at runtime, so they cannot be lookup keys. In this project BROWSER_STORAGE is a token for Storage, with a factory that returns localStorage in the browser and null on the server.', - }, - { - q: 'How does Angular resolve a dependency?', - a: 'It walks the element injector tree first, starting at the requesting element and going up through ancestor components. Then it walks the environment injectors: lazy route injectors, root, then platform. The first provider found wins. If none is found it throws NG0201, unless the request was optional. Modifiers like self, skipSelf and host change where the walk starts or stops.', - }, - { - q: 'inject() or constructor injection?', - a: 'They resolve the same way. inject() is the modern default: it works in field initialisers and functions (guards, interceptors, factories), plays well with inheritance because subclasses do not have to pass dependencies to super(), and does not depend on TypeScript decorator metadata. It must be called in an injection context.', - }, - { - q: 'How do you test a service that touches localStorage or the network?', - a: 'Put the dependency behind DI and override it in TestBed. Use { provide: TOKEN, useValue: fake } for a token, or provideHttpClientTesting() for HttpClient. The service code never changes between tests and production, and the tests never touch real global state.', - }, - ]; + protected readonly interview = INTERVIEW_BANK['angular-05-dependency-injection']; } diff --git a/src/app/thoughts-content/lessons/lesson-06-rxjs.ts b/src/app/thoughts-content/lessons/lesson-06-rxjs.ts index 3fe238d..1e7150c 100644 --- a/src/app/thoughts-content/lessons/lesson-06-rxjs.ts +++ b/src/app/thoughts-content/lessons/lesson-06-rxjs.ts @@ -4,6 +4,7 @@ import { delay, filter, Observable, of } from 'rxjs'; import { THOUGHTS } from '../thoughts-data'; import { Callout } from './callout'; import { CodeBlock } from './code-block'; +import { INTERVIEW_BANK } from './interview-bank'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; import { LessonSection } from './lesson-section'; @@ -298,30 +299,5 @@ provideHttpClient(withFetch(), withInterceptors([retryTransientErrors])),`, });`, }; - protected readonly interview = [ - { - q: 'switchMap, mergeMap, concatMap, exhaustMap: when do you use each?', - a: 'All four map a value to an inner Observable. switchMap cancels the previous inner stream, so use it when only the latest matters: search, route params. mergeMap runs them in parallel, for independent work. concatMap queues them in order, for writes that must not interleave. exhaustMap ignores new values while one is running, for a submit button double-click or a login request.', - }, - { - q: 'What is the difference between a hot and a cold Observable?', - a: 'A cold Observable starts its work separately for each subscriber: every subscribe to an HttpClient call sends a request. A hot one shares a single source that runs regardless, like DOM events or a Subject. You make a cold one shared with share() or shareReplay().', - }, - { - q: 'How do you avoid memory leaks with subscriptions in Angular?', - a: "Mostly by not subscribing manually: toSignal() and the async pipe unsubscribe when the component is destroyed. For a manual subscribe, use takeUntilDestroyed(), which takes a DestroyRef from the injection context. Streams that complete on their own, like a single HTTP call, don't leak, but they aren't cancelled either unless you unsubscribe.", - }, - { - q: 'Subject, BehaviorSubject, ReplaySubject?', - a: 'A Subject is both an Observable and an Observer: you push values in with next() and subscribers get them from then on. BehaviorSubject requires an initial value and gives new subscribers the current one immediately, which made it the service-store pattern before signals. ReplaySubject replays the last N values to late subscribers.', - }, - { - q: 'What is an HTTP interceptor, and what have you used one for?', - a: 'A function in the HttpClient pipeline that sees every request and its response Observable. Typical uses: adding auth headers, retrying, logging, turning errors into user messages, and caching. On my site one retries GETs that fail with a network error or 5xx, with exponential backoff, and never retries POSTs, because those are not safe to repeat.', - }, - { - q: 'Signals or RxJS?', - a: 'Both, at different jobs. Signals hold state that the UI reads synchronously. RxJS models events over time: debouncing, cancellation, retries, combining streams. A common shape is signal input, then toObservable, then the operators, then toSignal back out for the template.', - }, - ]; + protected readonly interview = INTERVIEW_BANK['angular-06-rxjs']; } diff --git a/src/app/thoughts-content/lessons/lesson-07-routing.ts b/src/app/thoughts-content/lessons/lesson-07-routing.ts index f91dd12..585d6f5 100644 --- a/src/app/thoughts-content/lessons/lesson-07-routing.ts +++ b/src/app/thoughts-content/lessons/lesson-07-routing.ts @@ -3,6 +3,7 @@ import { PRIMARY_OUTLET, UrlSerializer } from '@angular/router'; import { routes } from '../../app.routes'; import { Callout } from './callout'; import { CodeBlock } from './code-block'; +import { INTERVIEW_BANK } from './interview-bank'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; import { LessonSection } from './lesson-section'; @@ -242,30 +243,5 @@ readonly slug = input.required();`, ];`, }; - protected readonly interview = [ - { - q: 'How does the router decide which route matches?', - a: 'It walks the route array in order and takes the first route whose path fits, depth-first through children. So specific routes go before general ones, and the ** wildcard goes last. An empty-path redirect needs pathMatch: full, or it matches every URL by prefix.', - }, - { - q: 'How do you read route parameters in a component?', - a: 'Today, with withComponentInputBinding() enabled, declare an input with the param name and the router sets it, including on reuse. Without it, inject ActivatedRoute and use paramMap, an Observable, or toSignal(paramMap). Avoid route.snapshot in components the router may reuse, because it never updates.', - }, - { - q: 'What are guards and resolvers?', - a: 'Guards are functions that run during navigation. canActivate decides entry, canMatch decides whether a route is considered at all (good for feature flags and lazy loading), canDeactivate guards leaving, for example with unsaved changes. They can return a UrlTree to redirect. Resolvers fetch data before activation. Many apps now load in the component with resource() instead, so the page can render a loading state rather than blocking navigation.', - }, - { - q: 'How does lazy loading work with standalone components?', - a: 'loadComponent takes a function returning a dynamic import of a component, and loadChildren returns a routes array. The bundler splits each into its own chunk, fetched on first navigation. Preloading strategies, such as PreloadAllModules or a custom one, can fetch chunks in the background after startup.', - }, - { - q: 'Path params or query params?', - a: 'Path params identify the resource: /thoughts/:slug. Query params carry optional view state: sorting, filters, paging. With SSR or prerendering, anything that should be its own page with its own HTML and canonical URL needs to be in the path. On my site that is why tag pages are /thoughts/tag/:tag.', - }, - { - q: 'How do you test routing?', - a: 'With RouterTestingHarness: configure provideRouter with real routes, navigate by URL, and assert on the rendered component and router.url. It catches what mocked ActivatedRoute specs miss, such as component reuse on a param change. In my project a spec runs the real route table with the real app config, so a missing wildcard or router feature fails a test.', - }, - ]; + protected readonly interview = INTERVIEW_BANK['angular-07-routing']; } diff --git a/src/app/thoughts-content/lessons/lesson-08-forms.ts b/src/app/thoughts-content/lessons/lesson-08-forms.ts index 8ea11fb..998a3e8 100644 --- a/src/app/thoughts-content/lessons/lesson-08-forms.ts +++ b/src/app/thoughts-content/lessons/lesson-08-forms.ts @@ -2,6 +2,7 @@ import { ChangeDetectionStrategy, Component, inject } from '@angular/core'; import { FormBuilder, ReactiveFormsModule, ValidationErrors, ValidatorFn, Validators } from '@angular/forms'; import { Callout } from './callout'; import { CodeBlock } from './code-block'; +import { INTERVIEW_BANK } from './interview-bank'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; import { LessonSection } from './lesson-section'; @@ -291,30 +292,5 @@ contact.email().errors(); // a signal `, }; - protected readonly interview = [ - { - q: 'Reactive or template-driven forms?', - a: 'Template-driven forms build the model from ngModel in the template: quick for simple cases, but the logic is spread through HTML and hard to unit test. Reactive forms define the model in TypeScript, which makes them strongly typed, testable without a DOM, and better for dynamic fields, cross-field validation and complex flows. I default to reactive. In Angular 21, Signal Forms are an experimental third option built on signals.', - }, - { - q: 'How do you write a custom validator, and a cross-field one?', - a: 'A ValidatorFn takes a control and returns null when valid or an errors object like { blank: true }. For rules involving several fields, such as password confirmation or a date range, put the validator on the FormGroup so it sees every value and re-runs when any of them changes. Read it with group.hasError().', - }, - { - q: 'What does a ControlValueAccessor do?', - a: 'It is the bridge between a form control and a component or element. writeValue pushes the model into the view, registerOnChange and registerOnTouched give the component callbacks to report changes back, and setDisabledState handles disabling. Provide it with NG_VALUE_ACCESSOR as a multi provider, and formControlName and ngModel work on your component.', - }, - { - q: 'How do async validators work?', - a: 'They return an Observable or Promise of errors or null, and run only after the sync validators pass. While they run, the control status is PENDING. To avoid a request per keystroke, use updateOn: blur or debounce inside the validator with timer() and switchMap, since the validator is resubscribed on each value change.', - }, - { - q: 'How do you make a form accessible?', - a: 'Every input has a real label. Errors show once the field is touched, and are linked with aria-invalid and aria-describedby. The submit button stays enabled, and an invalid submit marks everything touched and focuses the first invalid field. Results go into a live region that already exists in the DOM. Use autocomplete attributes for personal data.', - }, - { - q: 'What changed with typed forms?', - a: 'Since Angular 14, FormControl, FormGroup and FormArray are generic and infer their types from initial values, so form.value.email is typed and typos are compile errors. nonNullable controls reset to their initial value instead of null, which removes string | null everywhere. UntypedFormGroup exists for migrating old code.', - }, - ]; + protected readonly interview = INTERVIEW_BANK['angular-08-forms']; } diff --git a/src/app/thoughts-content/lessons/lesson-09-change-detection.ts b/src/app/thoughts-content/lessons/lesson-09-change-detection.ts index 14569e3..68dcc5c 100644 --- a/src/app/thoughts-content/lessons/lesson-09-change-detection.ts +++ b/src/app/thoughts-content/lessons/lesson-09-change-detection.ts @@ -8,6 +8,7 @@ import { } from '@angular/core'; import { Callout } from './callout'; import { CodeBlock } from './code-block'; +import { INTERVIEW_BANK } from './interview-bank'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; import { LessonSection } from './lesson-section'; @@ -254,30 +255,5 @@ replace() { this.profile = { ...this.profile, visits: this.profile.visits + 1 }; });`, }; - protected readonly interview = [ - { - q: 'How does change detection work in Angular?', - a: 'Angular walks the component tree and re-evaluates template bindings, patching the DOM where values changed. With Zone.js, a pass ran after any async event because Angular could not know what changed. In a zoneless app, a pass is scheduled by signal changes, template events, markForCheck or setInput. OnPush and signals then narrow which components are actually checked.', - }, - { - q: 'When is an OnPush component checked?', - a: 'When one of its inputs receives a new reference, when an event fires in its template or a child, when a signal read in its template changes, or when markForCheck is called on it or a descendant (the async pipe does that). Mutating an object input in place triggers none of these.', - }, - { - q: 'What causes ExpressionChangedAfterItHasBeenChecked, and how do you fix it?', - a: 'In development mode Angular runs a second verification pass and throws if a binding changed after it was checked. That means state was changed during change detection itself: in ngAfterViewInit, by a child updating a parent, or by a getter returning a new object each time. Fix the data flow, for example by deriving the value with computed or setting it earlier. Wrapping it in setTimeout hides the bug and costs an extra render.', - }, - { - q: 'markForCheck vs detectChanges?', - a: 'markForCheck marks the view and its ancestors dirty so the next scheduled pass checks them. It is cheap and the usual choice. detectChanges synchronously runs change detection on that view and its children immediately, which is useful in tests or for detached views but easy to overuse.', - }, - { - q: 'How do signals change the picture?', - a: 'A signal knows exactly which views read it, so a change marks only those views for refresh, and Angular can skip OnPush ancestors. That is what makes zoneless practical: no global check after every event, and OnPush costs almost nothing to adopt when state is in signals.', - }, - { - q: 'How would you move a large app to OnPush?', - a: 'Component by component, leaves first, since they have the fewest dependencies. Look for plain fields mutated asynchronously, inputs mutated in place, and tests that rely on detectChanges after setting a field. Convert that state to signals or immutable updates. Then enforce it with the ESLint rule or a fitness test so new components start as OnPush. I did exactly that on my site and enforced it with a spec.', - }, - ]; + protected readonly interview = INTERVIEW_BANK['angular-09-change-detection']; } diff --git a/src/app/thoughts-content/lessons/lesson-10-directives.ts b/src/app/thoughts-content/lessons/lesson-10-directives.ts index 012c1a8..279d591 100644 --- a/src/app/thoughts-content/lessons/lesson-10-directives.ts +++ b/src/app/thoughts-content/lessons/lesson-10-directives.ts @@ -11,6 +11,7 @@ import { } from '@angular/core'; import { Callout } from './callout'; import { CodeBlock } from './code-block'; +import { INTERVIEW_BANK } from './interview-bank'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; import { LessonDemo } from './lesson-demo'; @@ -278,30 +279,5 @@ export class ScrollSpy { @Component({ selector: 'app-lesson', hostDirectives: [ScrollSpy], ... })`, }; - protected readonly interview = [ - { - q: 'What kinds of directives are there?', - a: 'Components, which are directives with a template; attribute directives, which change the appearance or behaviour of their host element; and structural directives, which add or remove DOM by rendering a TemplateRef into a ViewContainerRef. Since Angular 17 the built-in @if, @for and @switch blocks cover most structural needs without a directive.', - }, - { - q: 'What does the * in *ngIf do?', - a: 'It is shorthand. The element is wrapped in an , and the expression is bound to an input named after the directive selector. Microsyntax like "let item of items; trackBy: f" maps to more inputs, such as ngForOf and ngForTrackBy, and to template context variables.', - }, - { - q: 'What are host directives and why use them?', - a: 'hostDirectives on a component or directive applies other standalone directives to its host element, as if their attributes were written there. You pick which inputs and outputs to expose and can alias them. It is composition instead of inheritance: behaviour like focus handling, tooltips or scroll tracking can be shared without base classes, and consumers cannot forget to add it.', - }, - { - q: 'How do parent and child directives communicate?', - a: 'Through DI. A child injects the parent directive, optionally, from its element injector and registers itself, the way NgModel registers with NgForm or my headings register with ScrollSpy. The parent can also use contentChildren to query children. Registration keeps the parent generic, and queries are good when the parent needs an ordered list of children to render.', - }, - { - q: '@HostBinding and @HostListener vs the host property?', - a: 'Both do the same job. The Angular style guide now prefers the host property in the decorator metadata, because all host bindings sit in one place and work cleanly with signals. The decorators still work, and plenty of existing code uses them.', - }, - { - q: 'Where should DOM work in a directive happen?', - a: 'Not in the constructor, because children do not exist yet and on the server there is no browser DOM. Use afterNextRender or afterEveryRender for browser-only work like measuring or observers, and DestroyRef to clean up. Bindings in the host metadata are the safe way to write to the host element, since Angular applies them on the server too.', - }, - ]; + protected readonly interview = INTERVIEW_BANK['angular-10-directives']; } diff --git a/src/app/thoughts-content/lessons/lesson-11-testing.ts b/src/app/thoughts-content/lessons/lesson-11-testing.ts index bcc0df2..285c9cf 100644 --- a/src/app/thoughts-content/lessons/lesson-11-testing.ts +++ b/src/app/thoughts-content/lessons/lesson-11-testing.ts @@ -3,6 +3,7 @@ import type { AbstractControl, ValidationErrors } from '@angular/forms'; import { notBlank } from '../../shared/validators'; import { Callout } from './callout'; import { CodeBlock } from './code-block'; +import { INTERVIEW_BANK } from './interview-bank'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; import { LessonDemo } from './lesson-demo'; @@ -282,30 +283,5 @@ it('runs the production build', () => { });`, }; - protected readonly interview = [ - { - q: 'What do you test in an Angular component?', - a: 'Its behaviour through its public surface: what renders for given inputs, what happens on clicks and typing, which outputs it emits, and what it asks its services to do. Not private methods or internal fields, because those tests break on refactors that change nothing a user can see. I also run axe in component specs so accessibility regressions fail like any other bug.', - }, - { - q: 'How do you test a component that makes HTTP calls?', - a: 'Provide provideHttpClient() and provideHttpClientTesting(), then inject HttpTestingController. Trigger the behaviour, use expectOne to assert the request, flush a response or an error, and assert on the rendered result. verify() in afterEach fails the test if any request was left unanswered. For retries and debouncing, add fake timers so the test controls time.', - }, - { - q: 'Unit, integration or e2e?', - a: 'Mostly fast unit and component tests, because they pin behaviour cheaply and run on every save. Integration-style specs use the real config, for example routing tested against appConfig. A few e2e tests cover what needs a real browser: layout, scrolling, IntersectionObserver, and the critical user journeys. E2e tests are slow and more prone to flakiness, so each one should earn its place.', - }, - { - q: 'How do you test RxJS code?', - a: 'With marble tests on the RxJS TestScheduler. Inside scheduler.run(), every timer uses virtual time, so delays, debounces and races are deterministic and instant. You describe input streams as marble strings and assert the output against an expected one. For simple cases, subscribing and asserting after fake timers is fine too.', - }, - { - q: 'Karma and Jasmine vs Jest vs Vitest?', - a: 'Karma with Jasmine was the Angular default for years and ran tests in a real browser. New Angular 21 projects default to Vitest through the @angular/build:unit-test builder, which runs in jsdom with an optional browser mode. Jest was a common community choice in between. The TestBed API is the same in all of them, so most specs move between runners with little change.', - }, - { - q: 'Tell me about a test that caught something.', - a: 'On my site, a fitness test that reads the CI workflow showed that its typecheck step checked zero files. The root tsconfig only has project references, so plain tsc compiles nothing. CI had been green the whole time. The spec now requires the real tsconfigs, a production build, and a timeout on every job.', - }, - ]; + protected readonly interview = INTERVIEW_BANK['angular-11-testing']; } diff --git a/src/app/thoughts-content/lessons/lesson-12-ssr.ts b/src/app/thoughts-content/lessons/lesson-12-ssr.ts index b079332..5251965 100644 --- a/src/app/thoughts-content/lessons/lesson-12-ssr.ts +++ b/src/app/thoughts-content/lessons/lesson-12-ssr.ts @@ -9,6 +9,7 @@ import { } from '@angular/core'; import { Callout } from './callout'; import { CodeBlock } from './code-block'; +import { INTERVIEW_BANK } from './interview-bank'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; import { LessonDemo } from './lesson-demo'; @@ -244,30 +245,5 @@ afterNextRender(() => { }`, }; - protected readonly interview = [ - { - q: 'What is the difference between CSR, SSR and SSG?', - a: 'CSR renders in the browser: fast to serve, but nothing shows until the JavaScript runs, and crawlers see an empty shell. SSR renders on the server per request, so the HTML is complete and can depend on the request, at the cost of server time. SSG, or prerendering, renders once at build time and serves static files, which is the cheapest and fastest when content only changes on deploy. Angular 21 chooses per route with RenderMode.Client, Server and Prerender in the server routes.', - }, - { - q: 'What is hydration, and what breaks it?', - a: "Hydration is the browser adopting the server's DOM instead of re-creating it, so there's no flicker or lost scroll position. It needs the first client render to match the server's. It breaks when the two renders differ, for example a time, a random value or a locale, or when code changes the DOM outside Angular. Angular reports NG0500 for structural mismatches. ngSkipHydration opts a subtree out, but that's a workaround, not a fix.", - }, - { - q: 'How do you run code that needs the browser?', - a: 'afterNextRender for one-time setup and afterEveryRender for work after every render. Both only run in the browser, after the DOM exists. Inject DOCUMENT rather than touching the global, and provide browser APIs like localStorage through a token with a server fallback. isPlatformBrowser still exists, but render hooks are usually the better fit.', - }, - { - q: 'How do you avoid fetching data twice with SSR?', - a: "With hydration on, HttpClient's transfer cache stores GET and HEAD responses made on the server in TransferState, and the browser reuses them during hydration. For data that doesn't come through HttpClient, write it to TransferState yourself with makeStateKey on the server and read it in the browser.", - }, - { - q: 'What is incremental hydration?', - a: 'A @defer block with a hydrate trigger, such as hydrate on viewport, interaction or idle, renders fully on the server but stays dehydrated in the browser until the trigger fires, and its code is only downloaded then. Users see the content immediately while less JavaScript runs on load. hydrate never keeps static content static. It needs withIncrementalHydration() in provideClientHydration.', - }, - { - q: 'Tell me about an SSR bug you fixed.', - a: 'My site prerenders its blog pages, and every one of them shipped the menu bar clock as it was at build time. The bar was also marked ngSkipHydration, so the browser threw the server DOM away and rebuilt it. I made the clock render empty on the server, started it in afterNextRender, and removed ngSkipHydration so the bar hydrates. A spec renders the bar through the real server platform and asserts both.', - }, - ]; + protected readonly interview = INTERVIEW_BANK['angular-12-ssr']; } From 4fda8353a543fd68febc46f0ef91e6e161e26b34 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 11:36:50 -0500 Subject: [PATCH 3/6] Add an interview practice deck --- .../lessons/interview-practice.ts | 134 ++++++++++++++++++ .../lessons/lesson-13-interview.spec.ts | 4 +- 2 files changed, 137 insertions(+), 1 deletion(-) create mode 100644 src/app/thoughts-content/lessons/interview-practice.ts diff --git a/src/app/thoughts-content/lessons/interview-practice.ts b/src/app/thoughts-content/lessons/interview-practice.ts new file mode 100644 index 0000000..4e0474c --- /dev/null +++ b/src/app/thoughts-content/lessons/interview-practice.ts @@ -0,0 +1,134 @@ +import { + ChangeDetectionStrategy, + Component, + computed, + input, + linkedSignal, + signal, +} from '@angular/core'; +import type { InterviewQuestion } from './interview-questions'; + +export interface PracticeCard extends InterviewQuestion { + topic: string; +} + +const ALL_TOPICS = ''; + +/** + * [ng-13 interview] A flashcard deck over interview questions: read the + * question, answer it out loud, then check. "Got it" takes the card out; + * "Ask again" puts it at the back. + * + * The deck is a linkedSignal of the filtered cards: changing the topic or the + * cards resets it, and in between it's ordinary writable state (lesson 04). + * All three buttons are always rendered, so the one you just pressed keeps + * focus when the next card comes up. + */ +@Component({ + selector: 'app-interview-practice', + changeDetection: ChangeDetectionStrategy.OnPush, + template: ` +
+ + +

{{ deck().length }} left, {{ known() }} known

+
+ + @if (current(); as card) { +
+

{{ card.topic }}

+

{{ card.q }}

+

{{ card.a }}

+
+ + + +
+
+ } @else { +

That's the whole deck.

+ + } + `, + styles: ` + .practice-controls { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; + } + #practice-progress { + margin: 0 0 0 auto; + font-variant-numeric: tabular-nums; + } + .practice-card { + margin-top: 12px; + padding: 12px 16px; + border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1)); + border-radius: 8px; + } + .practice-topic { + margin: 0; + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.04em; + } + .practice-question { + font-weight: 600; + } + .practice-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + } + `, +}) +export class InterviewPractice { + readonly cards = input.required(); + + protected readonly allTopics = ALL_TOPICS; + protected readonly topic = signal(ALL_TOPICS); + protected readonly topics = computed(() => [...new Set(this.cards().map((card) => card.topic))]); + + private readonly filtered = computed(() => { + const topic = this.topic(); + return topic === ALL_TOPICS + ? this.cards() + : this.cards().filter((card) => card.topic === topic); + }); + + protected readonly deck = linkedSignal(() => this.filtered()); + protected readonly known = linkedSignal({ source: this.filtered, computation: () => 0 }); + protected readonly revealed = signal(false); + protected readonly current = computed(() => this.deck()[0]); + + protected markKnown(): void { + this.deck.update(([, ...rest]) => rest); + this.known.update((count) => count + 1); + this.revealed.set(false); + } + + protected askAgain(): void { + this.deck.update(([first, ...rest]) => [...rest, first]); + this.revealed.set(false); + } + + protected restart(): void { + this.deck.set(this.filtered()); + this.known.set(0); + this.revealed.set(false); + } +} diff --git a/src/app/thoughts-content/lessons/lesson-13-interview.spec.ts b/src/app/thoughts-content/lessons/lesson-13-interview.spec.ts index cfac03a..91b2b70 100644 --- a/src/app/thoughts-content/lessons/lesson-13-interview.spec.ts +++ b/src/app/thoughts-content/lessons/lesson-13-interview.spec.ts @@ -39,7 +39,9 @@ describe('Lesson13Interview', () => { it('practises every question in the guide, starting with lesson 01', () => { const total = Object.values(INTERVIEW_BANK).flat().length; - expect(el.querySelector('#practice-progress')?.textContent?.trim()).toBe(`${total} left, 0 known`); + expect(el.querySelector('#practice-progress')?.textContent?.trim()).toBe( + `${total} left, 0 known`, + ); expect(el.querySelector('#practice-topic')?.textContent?.trim()).toBe('Project structure'); }); From e4062f2a55ba48b04a0b5091b86b35b3b9359ccb Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 11:38:39 -0500 Subject: [PATCH 4/6] Write lesson 13 with practice over every question in the guide --- .../lessons/interview-bank.ts | 30 ++ .../lessons/lesson-13-interview.ts | 266 ++++++++++++++++++ src/app/thoughts-content/lessons/lessons.ts | 2 + src/app/thoughts-content/thoughts-bodies.ts | 4 + src/app/thoughts-content/thoughts-data.ts | 9 + 5 files changed, 311 insertions(+) create mode 100644 src/app/thoughts-content/lessons/lesson-13-interview.ts diff --git a/src/app/thoughts-content/lessons/interview-bank.ts b/src/app/thoughts-content/lessons/interview-bank.ts index c8e7ebb..ed00bc3 100644 --- a/src/app/thoughts-content/lessons/interview-bank.ts +++ b/src/app/thoughts-content/lessons/interview-bank.ts @@ -317,4 +317,34 @@ export const INTERVIEW_BANK: Record = { a: 'My site prerenders its blog pages, and every one of them shipped the menu bar clock as it was at build time. The bar was also marked ngSkipHydration, so the browser threw the server DOM away and rebuilt it. I made the clock render empty on the server, started it in afterNextRender, and removed ngSkipHydration so the bar hydrates. A spec renders the bar through the real server platform and asserts both.', }, ], + 'angular-13-interview': [ + { + q: 'What has changed in Angular over the last few major versions?', + a: 'Standalone components arrived in 14 and became the default in 19. Signals came in 16, built-in control flow and @defer in 17. Zoneless change detection went stable in 20 and is the default for new apps in 21, which also made Vitest the default test runner and introduced experimental Signal Forms. The direction is the same throughout: less framework magic, finer-grained reactivity, and smaller bundles.', + }, + { + q: 'How would you migrate an NgModule app to standalone and the new syntax?', + a: 'Upgrade one major version at a time with ng update until I am on a current version. Then run the standalone schematic, which works in passes: convert declarations, remove the NgModules that are now empty, then switch to bootstrapApplication. After that the control-flow, inject, signal input and output migrations. One schematic per change, with the tests green between each, so a regression points at one step.', + }, + { + q: 'When would you reach for NgRx?', + a: 'When a lot of state is shared across features, many parts of the app react to the same events, and the team wants one enforced pattern with devtools and action logs. For most apps, services that expose signals are enough, and that is what my own site uses. NgRx SignalStore is a middle ground: structured, but without actions and reducers.', + }, + { + q: 'Walk me through the NgRx data flow.', + a: 'A component dispatches an action, which describes something that happened. A reducer, a pure function, takes the current state and the action and returns new state. Selectors derive memoised slices of that state, which components read, as signals with selectSignal or as Observables. Effects listen for actions to run side effects such as HTTP calls, and dispatch new actions with the results.', + }, + { + q: 'What is the difference between AngularJS and Angular?', + a: 'AngularJS is version 1.x: JavaScript, controllers and $scope, digest-cycle dirty checking. Angular, from version 2 on, is a complete rewrite in TypeScript built on components, dependency injection and an ahead-of-time compiler. They share a name and little else. AngularJS support ended in 2021.', + }, + { + q: "What's the hardest Angular bug you've debugged?", + a: 'After moving every component on my site to OnPush, ng test and ng build finished their work and then never exited. I bisected the change in a separate worktree and dumped the handles keeping Node alive: an esbuild service process. The trigger was two components with byte-identical inline styles. I made the styles distinct, wrote it up, and added a timeout to every CI job so a hang fails in minutes instead of holding a runner for six hours.', + }, + { + q: 'Walk me through an Angular project you have built.', + a: 'My portfolio is a macOS-style desktop in Angular 21. The desktop shell is client-rendered, and the writing is prerendered per route for speed and SEO. State lives in services that expose signals; the menu bar, for example, is a computed signal derived from window and dock state. Windows are dynamic components. Every component is OnPush, a fitness test keeps it that way, and CI runs lint, both typechecks, unit tests with axe, a production build and e2e accessibility checks.', + }, + ], }; diff --git a/src/app/thoughts-content/lessons/lesson-13-interview.ts b/src/app/thoughts-content/lessons/lesson-13-interview.ts new file mode 100644 index 0000000..b642cd5 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-13-interview.ts @@ -0,0 +1,266 @@ +import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { THOUGHTS } from '../thoughts-data'; +import { Callout } from './callout'; +import { CodeBlock } from './code-block'; +import { INTERVIEW_BANK } from './interview-bank'; +import { InterviewPractice, PracticeCard } from './interview-practice'; +import { InterviewQuestions } from './interview-questions'; +import { Lesson } from './lesson'; +import { LessonDemo } from './lesson-demo'; +import { LessonSection } from './lesson-section'; + +/** "Angular 04: Signals" → "Signals". */ +function topicOf(slug: string): string { + const thought = THOUGHTS.find((entry) => entry.slug === slug); + if (!thought) throw new Error(`No thought for lesson "${slug}"`); + return thought.title.replace(/^Angular \d+: /, ''); +} + +@Component({ + selector: 'app-lesson-13-interview', + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ + Lesson, + LessonSection, + LessonDemo, + CodeBlock, + Callout, + InterviewQuestions, + InterviewPractice, + ], + template: ` + +

Simple

+

+ Most Angular codebases you'll join were started before standalone components and signals. + You need to read the older style fluently, and know how to move it forward. Here is one + component written the way it would have been in 2020. +

+ +

And the same component the way this site writes it:

+ +

+ Every change is one you've seen in this guide. declarations became + imports on the component (lesson 02). *ngIf and + *ngFor became @if and @for (lesson 03). + @Input became input(), the subscription became a + resource (lesson 04), and the constructor parameter became + inject() (lesson 05). +

+ +

+ Angular 19 flipped the default: components are standalone unless they say + standalone: false. In an older codebase, a component declared in an NgModule + has that flag set, and a new component you add to a module needs it too. +

+
+ +

Intermediate

+

+ Migrating. Angular ships schematics that do most of the mechanical work. + Run them one at a time, with the tests green between each, and upgrade one major version at + a time with ng update. +

+ +

+ NgRx. Many teams manage state with NgRx, so expect questions on it even + though this site doesn't use it. In the classic Store, components dispatch actions, + a pure reducer turns each action into new state, selectors read memoised + slices, and effects run side effects like HTTP and dispatch the results. +

+ +

+ The newer SignalStore drops actions and reducers for a signal-based service + builder. It sits between a hand-written service with signals, which is what this site uses, + and the full Store. +

+ + +

Expert

+

+ Talk about what you built and what broke. An interviewer can't check how + long you've used Angular, but they can tell within a few questions whether you've shipped + it. Specific stories with numbers do that better than any list of features. These all + happened while writing this guide: +

+
    +
  • + CI's typecheck had been checking zero files, because tsc ran against a root + tsconfig that only holds project references. A fitness test over the workflow found it + (lesson 11). +
  • +
  • + After moving every component to OnPush, ng test printed all green and never + exited. I bisected it to two components with identical inline styles keeping an esbuild + process alive, and added a timeout to every CI job (lessons 09 and 11). +
  • +
  • + Using DatePipe in a lazy page grew the initial bundle by 13 kB, because + @angular/common was already loaded eagerly. I replaced it with + Intl.DateTimeFormat, and made the same mistake again in lesson 12 (lessons 03 + and 12). +
  • +
  • + Every prerendered page showed the time the site was built, and the menu bar skipped + hydration to hide it. A spec on the real server platform now pins the fix (lesson 12). +
  • +
+

+ For each one, be ready to say how you found it, what you changed, and what stops it coming + back. The last part is what separates "I fixed a bug" from "I own this codebase". +

+ +

Pitfalls

+ +

+ Mixing up AngularJS and Angular. AngularJS (1.x) is a different + framework, built on controllers and $scope, and its support ended in 2021. + "Angular" means the TypeScript rewrite, from version 2 on. +

+
+ +

+ Only knowing the new syntax. If *ngIf, + @Input() or an NgModule throws you, it shows. Read both styles, and know + which migration gets from one to the other. +

+
+ +

+ NgRx by default. Saying you'd add a store to every app is a red flag. Say + what it costs (boilerplate, indirection) and when it pays: lots of shared state, many + features reacting to the same events, a team that wants one pattern. +

+
+ +

+ Claiming more than you can explain. Every line on your CV is a question + you might get. If you can't explain how something works, or tell a story about when it + went wrong, leave it off. +

+
+ +

Practice

+

+ Every interview question in this guide, one at a time. Answer out loud before you show the + answer; "Ask again" puts the card at the back of the deck. +

+ + + + +

Interview questions

+ +
+ `, +}) +export class Lesson13Interview { + protected readonly cards: PracticeCard[] = Object.entries(INTERVIEW_BANK).flatMap( + ([slug, questions]) => questions.map((question) => ({ ...question, topic: topicOf(slug) })), + ); + + protected readonly snippets = { + legacy: `@NgModule({ + declarations: [ProfileCardComponent], + imports: [CommonModule], + exports: [ProfileCardComponent], +}) +export class ProfileModule {} + +@Component({ + selector: 'app-profile-card', + standalone: false, + template: \` +
+ {{ tag }} +
+ Loading… + \`, +}) +export class ProfileCardComponent implements OnInit, OnDestroy { + @Input() userId!: string; + user?: User; + private destroy$ = new Subject(); + + constructor(private users: UserService) {} + + ngOnInit() { + this.users + .get(this.userId) + .pipe(takeUntil(this.destroy$)) + .subscribe((user) => (this.user = user)); + } + + ngOnDestroy() { + this.destroy$.next(); + this.destroy$.complete(); + } + + trackByTag(_index: number, tag: string) { + return tag; + } +}`, + modern: `@Component({ + selector: 'app-profile-card', + changeDetection: ChangeDetectionStrategy.OnPush, + template: \` + @if (user.value(); as user) { + @for (tag of user.tags; track tag) { + {{ tag }} + } + } @else { + Loading… + } + \`, +}) +export class ProfileCard { + private readonly users = inject(UserService); + readonly userId = input.required(); + readonly user = resource({ + params: () => this.userId(), + loader: ({ params: id }) => this.users.getOnce(id), + }); +}`, + migrations: `ng update @angular/core@20 @angular/cli@20 # one major at a time +ng generate @angular/core:standalone # NgModules to standalone, in three passes +ng generate @angular/core:control-flow # *ngIf / *ngFor to @if / @for +ng generate @angular/core:inject # constructor parameters to inject() +ng generate @angular/core:signal-input-migration +ng generate @angular/core:output-migration`, + ngrxStore: `export const loadRepos = createAction('[Projects Page] Load Repos'); +export const reposLoaded = createAction('[Projects API] Repos Loaded', props<{ repos: Repo[] }>()); + +export const projectsReducer = createReducer( + initialState, + on(loadRepos, (state) => ({ ...state, loading: true })), + on(reposLoaded, (state, { repos }) => ({ ...state, loading: false, repos })), +); + +export const selectRepos = createSelector(selectProjects, (state) => state.repos); + +export const loadRepos$ = createEffect( + (actions$ = inject(Actions), api = inject(GithubApi)) => + actions$.pipe( + ofType(loadRepos), + exhaustMap(() => api.repos().pipe(map((repos) => reposLoaded({ repos })))), + ), + { functional: true }, +); + +// In a component: +readonly repos = inject(Store).selectSignal(selectRepos);`, + signalStore: `export const ProjectsStore = signalStore( + { providedIn: 'root' }, + withState({ repos: [] as Repo[], loading: false }), + withComputed(({ repos }) => ({ count: computed(() => repos().length) })), + withMethods((store, api = inject(GithubApi)) => ({ + async load() { + patchState(store, { loading: true }); + patchState(store, { repos: await api.reposOnce(), loading: false }); + }, + })), +);`, + }; + + protected readonly interview = INTERVIEW_BANK['angular-13-interview']; +} diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts index 166ab89..1121d61 100644 --- a/src/app/thoughts-content/lessons/lessons.ts +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -24,4 +24,6 @@ export const LESSON_PAGES: Record Promise>> = { 'angular-10-directives': () => import('./lesson-10-directives').then((m) => m.Lesson10Directives), 'angular-11-testing': () => import('./lesson-11-testing').then((m) => m.Lesson11Testing), 'angular-12-ssr': () => import('./lesson-12-ssr').then((m) => m.Lesson12Ssr), + 'angular-13-interview': () => + import('./lesson-13-interview').then((m) => m.Lesson13Interview), }; diff --git a/src/app/thoughts-content/thoughts-bodies.ts b/src/app/thoughts-content/thoughts-bodies.ts index 6f8e1c0..c9a0bf7 100644 --- a/src/app/thoughts-content/thoughts-bodies.ts +++ b/src/app/thoughts-content/thoughts-bodies.ts @@ -281,4 +281,8 @@ The same lesson caught me out a second time. A test I wrote to pin a claim from 'angular-12-ssr': `Every Thoughts page on this site is prerendered at build time, and every one of them shipped the menu bar clock as it read during the build. Open a page a week later and the bar showed last week's time until the JavaScript loaded. The bar was also marked ngSkipHydration, so the browser threw away the HTML the server sent and drew the whole bar again. The fix was small once I could see what the server actually sends: the clock renders empty on the server, starts in afterNextRender, and the bar hydrates like everything else. A spec renders it through the real server platform to keep it that way. The demo below tells you whether the page you're reading came from the server or from your browser.`, + + 'angular-13-interview': `This guide started because I wanted to be able to say I'm fluent in Angular and back it up. Twelve lessons in, the part that would actually come up in an interview was scattered across twelve pages, a handful of questions at the bottom of each. + +So the last lesson pulls them together. Every lesson's questions now live in one bank, and the practice deck below drills all of them, one card at a time. Around it is what the other lessons skipped: the NgModule-era Angular most jobs still run, the schematics that migrate it, NgRx, and how to turn the bugs from this guide into answers.`, }; diff --git a/src/app/thoughts-content/thoughts-data.ts b/src/app/thoughts-content/thoughts-data.ts index fe14339..b291f97 100644 --- a/src/app/thoughts-content/thoughts-data.ts +++ b/src/app/thoughts-content/thoughts-data.ts @@ -296,4 +296,13 @@ export const THOUGHTS: ThoughtEntry[] = [ tags: ['angular-guide', 'ssr', 'angular'], relatedApp: 'readme', }, + { + slug: 'angular-13-interview', + title: 'Angular 13: Interview prep', + date: '2026-11-21', + summary: + 'The older Angular you will meet at work, how to migrate it, NgRx, and how to talk about what you have built. Ends with a practice deck of every interview question in the guide.', + tags: ['angular-guide', 'interview', 'angular'], + relatedApp: 'readme', + }, ]; From 671eaf5ce7445b0d77ddcca43f861d87ba64fab2 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 11:39:52 -0500 Subject: [PATCH 5/6] Find NgModules with the parser so lesson code samples don't count --- src/app/architecture.spec.ts | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/app/architecture.spec.ts b/src/app/architecture.spec.ts index 6253df9..699e790 100644 --- a/src/app/architecture.spec.ts +++ b/src/app/architecture.spec.ts @@ -39,17 +39,21 @@ function staticRelativeImports(file: string): string[] { } /** - * Real `@Component(...)` decorators on classes, read with the TypeScript - * parser. A text search also matches the code samples the lessons print. + * Real `@Component(...)`, `@NgModule(...)` etc. decorators on classes, read + * with the TypeScript parser. A text search also matches the code samples the + * lessons print. */ -function componentDecorators(file: string): { file: string; className: string; metadata: string }[] { +function classDecorators( + file: string, + decoratorName: string, +): { file: string; className: string; metadata: string }[] { const source = ts.createSourceFile(file, readFileSync(file, 'utf-8'), ts.ScriptTarget.Latest, true); const found: { file: string; className: string; metadata: string }[] = []; const visit = (node: ts.Node) => { if (ts.isClassDeclaration(node)) { for (const decorator of ts.getDecorators(node) ?? []) { const call = decorator.expression; - if (ts.isCallExpression(call) && ts.isIdentifier(call.expression) && call.expression.text === 'Component') { + if (ts.isCallExpression(call) && ts.isIdentifier(call.expression) && call.expression.text === decoratorName) { found.push({ file, className: node.name?.text ?? '(anonymous)', metadata: call.arguments[0]?.getText(source) ?? '' }); } } @@ -89,8 +93,8 @@ describe('[ng-01] architecture', () => { it('has no NgModules — every component, directive and pipe is standalone', () => { const withNgModule = files - .filter((file) => /@NgModule\s*\(/.test(readFileSync(file, 'utf-8'))) - .map((file) => relative(APP_ROOT, file)); + .flatMap((file) => classDecorators(file, 'NgModule')) + .map(({ file, className }) => `${relative(APP_ROOT, file)} (${className})`); expect(withNgModule).toEqual([]); }); @@ -100,7 +104,7 @@ describe('[ng-01] architecture', () => { // allowed only when written explicitly, so it is always a visible decision // rather than a forgotten line. it('every component sets OnPush, or opts into Eager explicitly', () => { - const decorators = files.flatMap(componentDecorators); + const decorators = files.flatMap((file) => classDecorators(file, 'Component')); const missing = decorators .filter(({ metadata }) => !/changeDetection:\s*ChangeDetectionStrategy\.(OnPush|Eager)\b/.test(metadata)) .map(({ file, className }) => `${relative(APP_ROOT, file)} (${className})`); @@ -111,7 +115,7 @@ describe('[ng-01] architecture', () => { it('the decorator finder skips @Component( inside code-sample strings', () => { const lesson02 = join(APP_ROOT, 'thoughts-content/lessons/lesson-02-components.ts'); - expect(componentDecorators(lesson02).map(({ className }) => className)).toEqual([ + expect(classDecorators(lesson02, 'Component').map(({ className }) => className)).toEqual([ 'DemoBadge', 'Lesson02Components', ]); From a0417d3caadc08a59a54c721e4d1aab00c6cb42a Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 11:40:13 -0500 Subject: [PATCH 6/6] Bump to 1.4.12 with the lesson 13 changelog entry --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bb5b526..1584dcd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ All notable changes to this project will be documented in this file. +## 2026-11-21 - version 1.4.12 + +- **Interview practice deck.** The last lesson ends with a flashcard deck of all 78 interview questions in the guide: one question at a time, the answer hidden until asked for, "Got it" to take a card out and "Ask again" to send it to the back, filterable by topic. The questions were scattered across twelve pages, a few at the bottom of each, which is no way to revise +- **Every lesson's questions live in one bank** (`interview-bank.ts`), keyed by lesson. Each lesson reads its own entry, and the deck reads all of them without importing twelve lesson components. A spec checks every lesson has at least five, none repeats, and each page renders its own. The cost: about 12 kB gzipped of question text now loads with the first lesson you open, instead of 1–3 kB per page +- **Angular guide, lesson 13: interview prep** (`/thoughts/angular-13-interview`). NgModule-era Angular side by side with the same component written today, the migration schematics, NgRx Store and SignalStore, and how to turn the bugs from this guide into interview answers +- **fix: the no-NgModules fitness test matched code samples.** Lesson 13 prints an `@NgModule` as an example, and the regex flagged it. It now reads real decorators with the TypeScript parser, the same fix the OnPush check got in 1.4.8 + ## 2026-11-21 - version 1.4.11 - **fix: prerendered pages showed the time the site was built.** The menu bar clock rendered on the server, so every Thoughts page shipped a frozen build-time clock until the JavaScript loaded. The clock now renders empty on the server and starts in `afterNextRender`, which only runs in the browser diff --git a/package-lock.json b/package-lock.json index 84edbd0..9929f4e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "angular-paul", - "version": "1.4.11", + "version": "1.4.12", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "angular-paul", - "version": "1.4.11", + "version": "1.4.12", "dependencies": { "@angular/common": "^21.2.0", "@angular/compiler": "^21.2.0", diff --git a/package.json b/package.json index ccdb7a8..005aeef 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-paul", - "version": "1.4.11", + "version": "1.4.12", "scripts": { "ng": "ng", "start": "ng serve",