From be5672bda6db4a025265268911c5115ab0cdffc6 Mon Sep 17 00:00:00 2001 From: Gabriel Matossian Date: Mon, 2 Nov 2026 16:47:56 -0800 Subject: [PATCH] Add accepted Angular fundamentals reference topics --- content/topics/angular-app-config/sources.md | 17 ++ content/topics/angular-app-config/topic.md | 82 ++++++ .../topics/angular-app-overview/sources.md | 16 ++ .../startup-and-components.svg | 251 ++++++++++++++++++ content/topics/angular-app-overview/topic.md | 64 +++++ .../sources.md | 11 + .../angular-component-communication/topic.md | 124 +++++++++ .../topics/angular-component-state/sources.md | 14 + .../topics/angular-component-state/topic.md | 93 +++++++ content/topics/angular-create-run/sources.md | 18 ++ content/topics/angular-create-run/topic.md | 114 ++++++++ .../angular-dev-proxy/local-api-proxy.svg | 237 +++++++++++++++++ content/topics/angular-dev-proxy/sources.md | 8 + content/topics/angular-dev-proxy/topic.md | 52 ++++ .../angular-forms-validation/sources.md | 28 ++ .../topics/angular-forms-validation/topic.md | 132 +++++++++ .../topics/angular-http-service/sources.md | 15 ++ content/topics/angular-http-service/topic.md | 130 +++++++++ .../topics/angular-provider-scope/sources.md | 10 + .../topics/angular-provider-scope/topic.md | 99 +++++++ .../angular-signals-observables/sources.md | 35 +++ .../angular-signals-observables/topic.md | 137 ++++++++++ content/topics/angular/topic.md | 15 ++ content/topics/javascript/topic.md | 15 ++ contracts/runtime-catalog.ts | 4 + docs/content-model.md | 1 + docs/content-storage.md | 10 +- e2e/app.spec.ts | 4 +- public/icons/topics/javascript.svg | 16 ++ public/icons/topics/tradeoff.svg | 20 ++ src/app/app.routes.spec.ts | 4 +- src/app/browse/topic-index-page.spec.ts | 10 +- src/app/catalog/catalog.service.spec.ts | 8 +- src/app/landing/landing-page.ts | 1 + src/app/ui/topic-icon/topic-icon.css | 4 +- tools/content/generate.spec.ts | 1 + tools/content/runtime-catalog.spec.ts | 2 + 37 files changed, 1786 insertions(+), 16 deletions(-) create mode 100644 content/topics/angular-app-config/sources.md create mode 100644 content/topics/angular-app-config/topic.md create mode 100644 content/topics/angular-app-overview/sources.md create mode 100644 content/topics/angular-app-overview/startup-and-components.svg create mode 100644 content/topics/angular-app-overview/topic.md create mode 100644 content/topics/angular-component-communication/sources.md create mode 100644 content/topics/angular-component-communication/topic.md create mode 100644 content/topics/angular-component-state/sources.md create mode 100644 content/topics/angular-component-state/topic.md create mode 100644 content/topics/angular-create-run/sources.md create mode 100644 content/topics/angular-create-run/topic.md create mode 100644 content/topics/angular-dev-proxy/local-api-proxy.svg create mode 100644 content/topics/angular-dev-proxy/sources.md create mode 100644 content/topics/angular-dev-proxy/topic.md create mode 100644 content/topics/angular-forms-validation/sources.md create mode 100644 content/topics/angular-forms-validation/topic.md create mode 100644 content/topics/angular-http-service/sources.md create mode 100644 content/topics/angular-http-service/topic.md create mode 100644 content/topics/angular-provider-scope/sources.md create mode 100644 content/topics/angular-provider-scope/topic.md create mode 100644 content/topics/angular-signals-observables/sources.md create mode 100644 content/topics/angular-signals-observables/topic.md create mode 100644 content/topics/angular/topic.md create mode 100644 content/topics/javascript/topic.md create mode 100644 public/icons/topics/javascript.svg create mode 100644 public/icons/topics/tradeoff.svg diff --git a/content/topics/angular-app-config/sources.md b/content/topics/angular-app-config/sources.md new file mode 100644 index 0000000..142df9e --- /dev/null +++ b/content/topics/angular-app-config/sources.md @@ -0,0 +1,17 @@ +# Authoring sources + +Retrieval job: recognize a concrete need for application-wide configuration and recover its provider entry, including the distinction between centralized error reporting and request-specific feedback. Targets Angular 22; reviewed 2026-10-31. + +- [ApplicationConfig](https://angular.dev/api/core/ApplicationConfig): providers available during bootstrap and to the root component and descendants. +- [provideBrowserGlobalErrorListeners](https://angular.dev/api/core/provideBrowserGlobalErrorListeners): listens to window error and unhandledrejection and forwards to ErrorHandler. +- [ErrorHandler](https://angular.dev/api/core/ErrorHandler): default console reporting and useClass replacement. +- [Unhandled errors](https://angular.dev/best-practices/error-handling): local handling for operation-specific recovery; global reporting is not UI recovery. +- [provideRouter](https://angular.dev/api/router/provideRouter): route provider setup. +- [HTTP setup](https://angular.dev/guide/http/setup): provideHttpClient with withInterceptors configures request features. Default HTTP availability is already covered by the related HTTP topic. +- [provideAppInitializer](https://angular.dev/api/core/provideAppInitializer): runs at startup in an injection context; loading language data is an explicit use case; returned Promise resolution or Observable completion delays initialization. +- [Dependency providers](https://angular.dev/guide/di/defining-dependency-providers): useClass replacement and providedIn root registration. +- [HTTP interceptors](https://angular.dev/guide/http/interceptors): shared request handling, authentication-header use case and withInterceptors registration. +- [Cognito access tokens](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-access-token.html): access tokens authorize API operations; the reader-facing example stays provider-neutral. +- [Using components](https://angular.dev/guide/components#using-components): component imports make template dependencies available. + +The optional examples are entries for an existing providers array, not complete files. routes, authInterceptor, loadStartupData and GlobalErrorHandler are application-defined identifiers; the reference does not implement routing, authentication, remote configuration or monitoring. The generic useValue/API_BASE_URL example, bootstrap plumbing and detached import-location paragraph were removed after owner retrieval review. No product exercise code is changed by this reference. diff --git a/content/topics/angular-app-config/topic.md b/content/topics/angular-app-config/topic.md new file mode 100644 index 0000000..44014aa --- /dev/null +++ b/content/topics/angular-app-config/topic.md @@ -0,0 +1,82 @@ +--- +id: '64c227ae-34fd-4c0d-bd8d-668c56205fc1' +title: 'Configure application-wide providers' +status: 'accepted' +summary: 'Recognize when to configure routing, shared HTTP behavior, startup work and global error reporting.' +iconKey: 'operations' +domains: + - 'javascript' +kind: 'operations' +childTopicIds: [] +relatedTopicIds: + - 'd48436d1-d79b-4e9a-bac5-9ff8672920f7' + - '6b2a1c19-acaa-4793-9e8a-7a783564bde5' +--- + +## Configure behavior used across the app + +Use **`app.config.ts`** to configure shared behavior, such as **navigation**, +**HTTP request rules** or the app's **default error handler**. Components can then use +that configuration without repeating the setup individually. + +```typescript +import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core'; + +export const appConfig: ApplicationConfig = { + providers: [provideBrowserGlobalErrorListeners()], +}; +``` + +> **Your service already has `providedIn: 'root'`?** Inject it directly; +> no extra registration is needed here. + +To **render a child component**, add it to the parent's component `imports`. + +## Add configuration when you need it + +**Give different screens their own URLs** → add `provideRouter(routes)`. + +**Send an access token with requests to your API** → register an HTTP +interceptor that adds `Authorization: Bearer `: + +```typescript +provideHttpClient(withInterceptors([authInterceptor])); +``` + +**Load essential data before the first screen appears**, such as the initial +language's translations → add `provideAppInitializer(loadStartupData)`. Return a +Promise or Observable from `loadStartupData`: startup **waits for it to resolve +or complete**. + +These are optional entries in `providers`. `routes`, `authInterceptor` and +`loadStartupData` are application code you supply. + +## Collect unexpected errors in one place + +`provideBrowserGlobalErrorListeners()` forwards uncaught browser failures to +Angular's `ErrorHandler` for centralized reporting: + +```text +Uncaught JavaScript error or +unhandled Promise rejection + ↓ + Angular ErrorHandler + ↓ + Console logging by default +``` + +To **send errors to an error-tracking service**, replace the default handler +with an entry in `providers`: + +```typescript +{ + provide: ErrorHandler, + useClass: GlobalErrorHandler, +}, +``` + +`GlobalErrorHandler` is your own implementation of `ErrorHandler`; its +`handleError(error)` method performs the reporting. + +**Reporting does not recover the UI.** Handle expected request failures near +the request, where you can show feedback such as “Product not found”. diff --git a/content/topics/angular-app-overview/sources.md b/content/topics/angular-app-overview/sources.md new file mode 100644 index 0000000..4320636 --- /dev/null +++ b/content/topics/angular-app-overview/sources.md @@ -0,0 +1,16 @@ +# Authoring sources + +Retrieval job: recognize the roles of the Angular app pieces encountered in the product exercise and identify when each becomes useful. Targets standalone Angular 22; checked 2026-10-31. Configuration and implementation syntax remain in the related operational references. + +- [Components](https://angular.dev/guide/components): class/template/selector, rendering child components, component tree. +- [bootstrapApplication](https://angular.dev/api/platform-browser/bootstrapApplication): chosen standalone root component and application configuration. +- [ApplicationConfig](https://angular.dev/api/core/ApplicationConfig): application-level provider setup. +- [Dependency injection](https://angular.dev/guide/di): dependencies supplied to consumers, sharing behavior and substituting test doubles. +- [Creating and using services](https://angular.dev/guide/di/creating-and-using-services): services and inject. +- [Defining providers](https://angular.dev/guide/di/defining-dependency-providers): provider recipes, automatic providedIn registration and explicit replacement. +- [Hierarchical injectors](https://angular.dev/guide/di/hierarchical-dependency-injection): application and local provider scopes, component sharing and injector lookup; detailed scope choice lives in the child reference. +- [HTTP interceptors](https://angular.dev/guide/http/interceptors): shared request/response behavior, authentication and logging examples, functional interceptor form. + +Product component names illustrate composition, not Angular-mandated filenames or special page component types. The startup/composition diagram adapts docs/design/diagrams/starter.svg and preserves the embedded font bytes and complete font licenses. Dependency injection uses a short sentence instead of a redundant diagram. No learner implementation or additional framework API is introduced here. + +2026-11-01 retrieval revision: distinguish Angular-supplied dependencies and feature registrations from providers the application author must register. HttpClient version details and the contextual DestroyRef example remain in the HTTP service reference. diff --git a/content/topics/angular-app-overview/startup-and-components.svg b/content/topics/angular-app-overview/startup-and-components.svg new file mode 100644 index 0000000..86ed8e2 --- /dev/null +++ b/content/topics/angular-app-overview/startup-and-components.svg @@ -0,0 +1,251 @@ + + Startup and component composition + main.ts uses app.config.ts and starts App, the root component. App renders ProductsPage, which renders the create form and product list. + +Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + + + + + + + + + main.ts + Starts the app + + app.config.ts + Shared setup + + uses + + + App + Root component + + renders + + ProductsPage + Page component + + + + renders + + Create form + Child component + + Product list + Child component + diff --git a/content/topics/angular-app-overview/topic.md b/content/topics/angular-app-overview/topic.md new file mode 100644 index 0000000..849d246 --- /dev/null +++ b/content/topics/angular-app-overview/topic.md @@ -0,0 +1,64 @@ +--- +id: 'd48436d1-d79b-4e9a-bac5-9ff8672920f7' +title: 'How an Angular app fits together' +status: 'accepted' +summary: 'Recognize components, services, providers and interceptors, and understand how startup and dependency injection connect them.' +iconKey: 'architecture' +domains: + - 'javascript' +kind: 'concept' +childTopicIds: + - 'fe994f41-dbc9-456c-b50e-53d3a4a9719c' + - '253aba39-8aed-4a85-94fb-7f09406e72d3' +relatedTopicIds: + - 'f7aa760f-30aa-43da-8746-20a39e39529e' + - '6b2a1c19-acaa-4793-9e8a-7a783564bde5' + - '64c227ae-34fd-4c0d-bd8d-668c56205fc1' +--- + +## Build the screen from components + +![main.ts uses app.config.ts to start App. App renders ProductsPage, which renders the create form and product list.](./startup-and-components.svg) + +- **Component:** a TypeScript class paired with a template; **owns a piece of UI**. + Split components when those pieces need their own behavior or can be reused. +- **Template:** HTML with Angular bindings for **displaying state and responding + to events**. +- **Root component:** the **first component Angular renders**, usually `App`. + Use it to compose the application's outer layout. “Page” and “child” are + **roles, not special component types**. +- **Application configuration (`app.config.ts`):** shared setup, such as routing, + HTTP interceptors or the default error handler. Configure it when the **same + behavior should apply across the app**. + +`main.ts` selects the root component and configuration when starting Angular. + +## Reuse behavior through services and DI + +Components, services and interceptors can use **`inject(...)` to request +dependencies**; Angular supplies instances using their providers. + +Angular supplies some built-in dependencies automatically. Others become +available when you configure a feature, so **not every injected dependency +needs your own `providers` entry**. + +- **Service:** a class containing behavior that can be used **independently of a + particular template**. Put product API calls here so components can use them + without each repeating the HTTP code. +- **Dependency injection (DI):** **Angular supplies a class's dependencies** instead + of the class constructing them. This lets components share a service and lets + tests substitute a fake implementation. +- **Provider:** a registration telling Angular **what to supply** for a requested + dependency. +- **Provider scope:** determines **where the dependency is available and which + consumers share it**. Register application-wide services with `providedIn: 'root'` + or application configuration; use route, component or directive providers for + narrower scopes. Module-based apps also support module providers. +- **Injector:** Angular's dependency resolver. It **looks up providers and supplies + the dependencies**. + +## Apply shared HTTP behavior + +**Interceptor:** a function in Angular's **HTTP request/response pipeline**. Use one +when several API calls need the **same authentication header or request logging**, +so each service method does not repeat that behavior. A basic product lookup needs no custom interceptor. diff --git a/content/topics/angular-component-communication/sources.md b/content/topics/angular-component-communication/sources.md new file mode 100644 index 0000000..d692572 --- /dev/null +++ b/content/topics/angular-component-communication/sources.md @@ -0,0 +1,11 @@ +# Authoring sources + +Retrieval job: choose an explicit component boundary and recover the syntax for parent/child data, action events and imperative UI methods. Targets Angular 22; drafted 2026-11-02. + +- [Inputs](https://angular.dev/guide/components/inputs): required input signals, parent binding, read-only signals versus mutable referenced objects. +- [Outputs](https://angular.dev/guide/components/outputs): typed output emitters and $event payloads; outputs are not browser events or RxJS Observables. +- [Child queries](https://angular.dev/guide/components/queries): signal view queries, required/optional results, view lifetime and conditional children. +- [Component composition](https://angular.dev/guide/components#using-components): parent imports and selectors. +- [Style guide](https://angular.dev/style-guide): UI responsibilities and separation of behavior. Container/presentational boundaries here are contextual design advice, not an Angular-enforced architecture. + +The ProductRow example is a self-contained reference with a two-field local Product shape, not a change to the learner exercise. Parent event handling only selects an edit target; it does not implement an editor or HTTP mutation. The final dialog fragment assumes an existing dialog with a public open(Product) method; query availability and required-child preconditions are stated. Detailed form handling and HTTP lifecycle belong to the related topics. No new dependencies or changes to the exercise are required. diff --git a/content/topics/angular-component-communication/topic.md b/content/topics/angular-component-communication/topic.md new file mode 100644 index 0000000..defdc34 --- /dev/null +++ b/content/topics/angular-component-communication/topic.md @@ -0,0 +1,124 @@ +--- +id: '88a16c45-cb2c-45e5-a067-445166a3f509' +title: 'Pass data and events between components' +status: 'accepted' +summary: 'Choose inputs, outputs, child methods or service injection, and make component dependencies explicit.' +iconKey: 'operations' +domains: + - 'javascript' +kind: 'pattern' +childTopicIds: [] +relatedTopicIds: + - '6b2a1c19-acaa-4793-9e8a-7a783564bde5' + - '8f0eac15-f8c7-4a92-80bb-0c45ff6b4e87' +--- + +## Choose the boundary + +| Need | Use | +| ------------------------------------- | ---------------------------- | +| Supply data to a child | `input()` + `[property]` | +| Receive an action from a child | `output()` + `(event)` | +| Open or focus child UI | `viewChild()` + child method | +| Access API or shared feature behavior | Inject a service | + +**Inputs and outputs define a data/event contract.** A child that also injects +an API service still depends on that service. + +## Pass data down and actions up + +```text +ProductsPage ── [product] ───────→ ProductRow +ProductsPage ←─ (editRequested) ── ProductRow +``` + +**`product-row.ts`** + +```typescript +import { Component, input, output } from '@angular/core'; + +export interface Product { + id: string; + name: string; +} + +@Component({ + selector: 'app-product-row', + template: ` + {{ product().name }} + + `, +}) +export class ProductRow { + readonly product = input.required(); + readonly editRequested = output(); +} +``` + +**`products-page.ts`** + +```typescript +import { Component, signal } from '@angular/core'; +import { Product, ProductRow } from './product-row'; + +@Component({ + imports: [ProductRow], + template: ` + + @if (editingProduct(); as product) { +

Editing {{ product.name }}

+ } + `, +}) +export class ProductsPage { + protected readonly selectedProduct = signal({ id: 'p1', name: 'Notebook' }); + protected readonly editingProduct = signal(null); + + protected beginEdit(product: Product): void { + this.editingProduct.set(product); + } +} +``` + +- **Read an input with `product()`**; `input.required` requires the parent binding. +- **`$event` is the emitted payload** — here a `Product`, not a browser event. +- **Emit an action instead of mutating the input object.** Read-only input signals + do not make the objects they hold deeply immutable. + +## Choose who calls the API + +| Put API calls in… | When it fits | Cost | +| ---------------------- | --------------------------------- | --------------------------------------- | +| Parent/coordinator | Reuse the child across features | Parent handles events and request state | +| Feature-specific child | Child owns that feature operation | Child depends on the API service | + +A reusable form can still own **controls, validation and local interaction state**. +The parent can receive submitted values and call the service. These roles are +sometimes called container/smart and presentational/dumb; they are **design choices, +not Angular component types**. + +## Call a child method for a UI action + +For an existing `ProductEditDialog` with an `open(product)` method, the parent +renders the child and calls its public method: + +```angular-html + + +``` + +```typescript +private readonly editor = viewChild.required(ProductEditDialog); + +protected openEditor(product: Product): void { + this.editor().open(product); +} +``` + +The parent imports `ProductEditDialog` in its component `imports`. +**`viewChild` finds the rendered child; it does not create one.** Access it after +rendering, such as from a click handler. `required` assumes the child is present; +for a conditional child, use `viewChild(ProductEditDialog)` and check for `undefined`. + +The parent now depends on the child's **method API**. Use this for actions such as +open/focus; use inputs and outputs for ordinary data and event exchange. diff --git a/content/topics/angular-component-state/sources.md b/content/topics/angular-component-state/sources.md new file mode 100644 index 0000000..8c11be5 --- /dev/null +++ b/content/topics/angular-component-state/sources.md @@ -0,0 +1,14 @@ +# Authoring sources + +Retrieval job: recover a standalone component/template pair with signal-backed list state and the syntax needed to display and change it. Targets Angular 22; verified 2026-10-30. + +- [Component anatomy](https://angular.dev/guide/components): metadata, relative template/style paths, standalone imports and selector composition. +- [Angular signals](https://angular.dev/guide/signals): read/set/update and default equality; deep mutation is not prevented or independently notified. +- [Template bindings](https://angular.dev/guide/templates/binding): interpolation and property bindings; reading signals in templates. +- [Event listeners](https://angular.dev/guide/templates/event-listeners): event-handler syntax. +- [Control flow](https://angular.dev/guide/templates/control-flow): for/track/empty and built-in control flow. Tracking is required; prefer stable unique keys for changing collections, and $index for static collections. Tracking guidance reviewed 2026-11-01. +- [Style guide](https://angular.dev/style-guide): protected template members and readonly references. + +Snippets are purpose-built reference examples. Local sample IDs are preview data, not the UUID API model. Compile/render verification is performed in a scratch Angular workspace, separate from the learner exercise. + +- [Using components](https://angular.dev/guide/components#using-components): standalone components are directly imported by consuming components; standalone defaults to true from Angular 19. Parent example replaces the former metadata-label table; composition wording reviewed 2026-11-02. diff --git a/content/topics/angular-component-state/topic.md b/content/topics/angular-component-state/topic.md new file mode 100644 index 0000000..63d85af --- /dev/null +++ b/content/topics/angular-component-state/topic.md @@ -0,0 +1,93 @@ +--- +id: 'f7aa760f-30aa-43da-8746-20a39e39529e' +title: 'Components and template state' +status: 'accepted' +summary: 'Recover component composition, signal-backed state, bindings, and list rendering.' +iconKey: 'operations' +domains: + - 'javascript' +kind: 'operations' +childTopicIds: + - '88a16c45-cb2c-45e5-a067-445166a3f509' +relatedTopicIds: + - '253aba39-8aed-4a85-94fb-7f09406e72d3' +--- + +## Component and template + +**`product-preview.ts`** + +```typescript +import { Component, signal } from '@angular/core'; + +@Component({ + selector: 'app-product-preview', + templateUrl: './product-preview.html', +}) +export class ProductPreview { + protected readonly products = signal([{ id: 1, name: 'Notebook' }]); + + protected clear(): void { + this.products.set([]); + } +} +``` + +**`product-preview.html`** + +```angular +

{{ products().length }} products

+ + + +
    + @for (product of products(); track product.id) { +
  • {{ product.name }}
  • + } @empty { +
  • No products
  • + } +
+``` + +## Use a component in another template + +A **standalone component** can be imported directly in the parent's `imports`; +it does not need an `NgModule` declaration. **Angular 19+ defaults to standalone**, +so these examples omit `standalone: true`. + +```typescript +import { Component } from '@angular/core'; +import { ProductPreview } from './product-preview'; + +@Component({ + imports: [ProductPreview], + template: '', +}) +export class ProductsPage {} +``` + +## Read and change state + +Signals retain **current template state** and notify Angular when it changes. + +- **Read:** `products()`; omitting `()` refers to the signal itself. +- **Replace:** `products.set(nextProducts)`. +- **Derive a new value:** `products.update(current => [...current, nextProduct])`. + +**Return a new array/object when changing signal state.** Mutating the current +array with `push()` does not itself notify signal consumers. + +The template uses **`{{ ... }}` for text**, **`[property]` for values** and +**`(event)` for handlers**. + +`protected` members remain usable by the template. A `readonly` signal field +prevents replacing the signal reference; **`.set()` and `.update()` still work**. + +## Render a list + +- **`track` is required.** Use a stable unique key, such as `track product.id`, + so Angular can reuse rows when data changes or a refresh returns new objects. +- **Use `track $index` for static lists** whose membership and order never change. + +`@empty` renders when the collection is empty. Built-in control flow needs no +`CommonModule` import. diff --git a/content/topics/angular-create-run/sources.md b/content/topics/angular-create-run/sources.md new file mode 100644 index 0000000..bf85c0c --- /dev/null +++ b/content/topics/angular-create-run/sources.md @@ -0,0 +1,18 @@ +# Authoring sources + +Verified against Angular's official documentation on 2026-10-29; commands target Angular CLI 22. + +- [ng new](https://angular.dev/cli/new): workspace name versus directory, standalone default, routing, SSR, CSS, defaults and skip-git options. +- [Installation](https://angular.dev/installation): creation installs dependencies; generated npm start script. +- [Version compatibility](https://angular.dev/reference/versions): supported Node lines; Angular 22 with Node 24 requires ^24.15.0. +- [Workspace file structure](https://angular.dev/reference/configs/file-structure): bootstrap, app config and default concise component filenames. +- [ng serve](https://angular.dev/cli/serve): port selection and development serving. +- [ng test](https://angular.dev/cli/test): watch=false for one test run. +- [ng build](https://angular.dev/cli/build): production build and output directory. +- [npm ci](https://docs.npmjs.com/cli/v11/commands/npm-ci): lockfile-based clean installation. + +- [ng generate component](https://angular.dev/cli/generate/component): component filenames, standalone default, flat layout and generated tests. Checked 2026-10-30 against the learner project's Angular CLI 22.2.5; a flat component dry run produced TypeScript, HTML, CSS and spec files without creating them. +- [ng generate](https://angular.dev/cli/generate): generate/g alias and dry-run preview option. +- [Importing and using components](https://angular.dev/guide/components/importing): parent imports and template selector for standalone composition. + +- [Serving Angular apps for development](https://angular.dev/tools/cli/serve): explicit proxyConfig setup and restart requirement. Reviewed 2026-11-01. Local debugging confirmed a server started without proxy configuration returned the Angular HTML document for GET /products with HTTP 200; Gabriel confirmed restarting with --proxy-config resolved the issue. diff --git a/content/topics/angular-create-run/topic.md b/content/topics/angular-create-run/topic.md new file mode 100644 index 0000000..3eb4e9d --- /dev/null +++ b/content/topics/angular-create-run/topic.md @@ -0,0 +1,114 @@ +--- +id: '5dd196fa-28a4-4a60-9aaf-26553d7067ec' +title: 'Create and run an Angular app' +status: 'accepted' +summary: 'Create an Angular workspace, generate components, locate key files, and recover run, test, and build commands.' +iconKey: 'operations' +domains: + - 'javascript' +kind: 'operations' +childTopicIds: + - 'f7aa760f-30aa-43da-8746-20a39e39529e' + - '8f0eac15-f8c7-4a92-80bb-0c45ff6b4e87' + - '6b2a1c19-acaa-4793-9e8a-7a783564bde5' + - '64c227ae-34fd-4c0d-bd8d-668c56205fc1' +relatedTopicIds: + - 'b35c83b3-ae4d-405b-a06c-21bc3d24bfd5' +--- + +## Create the skeleton + +Run from the **existing backend project root**. This creates a separate Angular +workspace in `ui/`, beside `pom.xml` and the backend's `src/`. + +```bash +node --version +npx @angular/cli@22 new products-ui --directory ui \ + --routing=false --ssr=false --style=css --skip-git --defaults +cd ui +``` + +For Angular 22, **Node 24.x must be 24.15.0 or newer**. Other supported Node +lines are listed in Angular's [version compatibility table](https://angular.dev/reference/versions). + +| Option | Effect | +| ----------------------------- | ---------------------------------------------------------------- | +| `--directory ui` | Workspace folder; the Angular project name remains `products-ui` | +| `--routing=false --ssr=false` | One-page client-rendered starting point | +| `--skip-git` | Keep the existing repository; do not initialize another | + +Standalone components are **the default**. Dependencies are **installed during creation**. + +## Run, test, build + +Run from **`ui/`**, containing `package.json` and `angular.json`. + +```bash +# Develop — port 4201 +npm start -- --port 4201 + +# Develop with an existing API proxy file +npm start -- --port 4201 --proxy-config src/proxy.conf.json + +# Test once +npm test -- --watch=false + +# Production build → dist/ +npm run build + +# Restore locked dependencies +npm ci +``` + +Development serves `http://localhost:4201` and **reloads after edits**. +The production build creates files; it **does not deploy**. + +`npm start` uses the workspace's CLI. **4200 is the default**; use another port +when it is occupied. Stop the development server with `Ctrl+C`. + +> **Creating the proxy file does not enable it.** Pass `--proxy-config` when +> starting the server, or set `serve.options.proxyConfig` in `angular.json`. +> Restart after changing proxy configuration. + +If an API request returns **`200 OK` with the app's HTML instead of JSON**, +check that the proxy is enabled and matches the request path. `HttpClient` +reports a JSON parsing error even though the HTTP status is successful. + +## Generate a component + +Run from **`ui/`**: + +```bash +npx ng generate component \ + products/product-list --flat +``` + +**Short form:** `ng g c` means `ng generate component`. + +```text +src/app/products/ +├── product-list.ts +├── product-list.html +├── product-list.css +└── product-list.spec.ts +``` + +- **`--flat`:** keep files directly in `products/`. Omit it to create a + `products/product-list/` directory. +- **`--dry-run`:** preview generated files **without writing changes**. + +Add the standalone component to its parent's **`imports`**, then use its +**selector** in the parent template. Generation **does not embed the component +or move existing HTML/CSS**. + +## Where to edit + +| File inside `ui/` | Responsibility | +| --------------------------- | --------------------------------------- | +| `src/app/app.{ts,html,css}` | **Root component** | +| `src/app/app.config.ts` | Application-wide **providers** | +| `src/main.ts` | **Bootstrap** the app | +| `angular.json` | **Build, serve and test** configuration | + +These are the default concise filenames; older projects may use +`app.component.ts` and `app.component.html`. diff --git a/content/topics/angular-dev-proxy/local-api-proxy.svg b/content/topics/angular-dev-proxy/local-api-proxy.svg new file mode 100644 index 0000000..b22d448 --- /dev/null +++ b/content/topics/angular-dev-proxy/local-api-proxy.svg @@ -0,0 +1,237 @@ + + Local Angular API proxy + Requests go from the browser to Angular at localhost:4201, then through its development proxy to Spring at localhost:8080. The /products path is retained. + + +Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + + + + + + + + + Browser + /products + + + Angular dev server + localhost:4201 + + proxy + + Spring API + localhost:8080 + diff --git a/content/topics/angular-dev-proxy/sources.md b/content/topics/angular-dev-proxy/sources.md new file mode 100644 index 0000000..96ab726 --- /dev/null +++ b/content/topics/angular-dev-proxy/sources.md @@ -0,0 +1,8 @@ +# Authoring sources + +Verified on 2026-10-29. Example targets @angular/build:dev-server and the existing Spring API's /products routes. + +- [Serving Angular apps for development](https://angular.dev/tools/cli/serve#proxying-to-a-backend-server): JSON proxy configuration, CLI option, restart requirement, and current /path/** matching semantics. +- [ng serve](https://angular.dev/cli/serve): proxy-config and port CLI options. +- [MDN: Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS): browser-origin boundary when contacting the backend directly. +- Diagram adapted from docs/design/diagrams/starter.svg; embedded font data and licenses preserved. Diagram shows request direction only; responses return through the proxy. diff --git a/content/topics/angular-dev-proxy/topic.md b/content/topics/angular-dev-proxy/topic.md new file mode 100644 index 0000000..2587c47 --- /dev/null +++ b/content/topics/angular-dev-proxy/topic.md @@ -0,0 +1,52 @@ +--- +id: 'b35c83b3-ae4d-405b-a06c-21bc3d24bfd5' +title: 'Proxy Angular development requests to an API' +status: 'accepted' +summary: 'Forward relative /products requests to Spring Boot without changing the browser-facing origin.' +iconKey: 'network' +domains: + - 'javascript' + - 'http' +kind: 'operations' +childTopicIds: [] +relatedTopicIds: [] +--- + +## Local request path + +![The browser sends /products to the Angular dev server at localhost:4201. The dev server proxies the request to the Spring API at localhost:8080, retaining /products.](./local-api-proxy.svg) + +## Configure and run + +Create **`ui/src/proxy.conf.json`**: + +```json +{ + "/products/**": { + "target": "http://localhost:8080" + } +} +``` + +From **`ui/`**: + +```bash +npm start -- --port 4201 --proxy-config src/proxy.conf.json +``` + +| Request path in frontend code | Forwarded destination | +| ----------------------------- | ------------------------------------- | +| `/products` | `http://localhost:8080/products` | +| `/products/UUID` | `http://localhost:8080/products/UUID` | + +With the current `@angular/build:dev-server`, `/products/**` matches the base +path **and nested paths**. No path rewrite is needed for this API. + +## Avoid these traps + +- Use **relative URLs** in frontend code. Calling `http://localhost:8080` + directly bypasses the proxy and requires the API's CORS configuration. +- Run Spring Boot separately; the proxy **does not start the API**. +- **Restart `ng serve` after changing proxy configuration.** +- This is **development-server configuration**. A production host needs its own + reverse proxy/routing, or an explicit API origin with appropriate CORS. diff --git a/content/topics/angular-forms-validation/sources.md b/content/topics/angular-forms-validation/sources.md new file mode 100644 index 0000000..b69628e --- /dev/null +++ b/content/topics/angular-forms-validation/sources.md @@ -0,0 +1,28 @@ +# Authoring sources + +Retrieval job: recover reactive-form wiring and choose where validation rules live. Targets Angular 22; reviewed 2026-11-02. + +- [Reactive forms](https://angular.dev/guide/forms/reactive-forms): FormGroup/FormControl, ReactiveFormsModule, formControlName and ngSubmit. +- [Validation](https://angular.dev/guide/forms/form-validation): validator placement, errors/touched feedback, disabled native validation and server validation. +- [RequiredValidator](https://angular.dev/api/forms/RequiredValidator), [MaxLengthValidator](https://angular.dev/api/forms/MaxLengthValidator), [PatternValidator](https://angular.dev/api/forms/PatternValidator): attribute directives support reactive controls, not only ngModel. +- [Validators](https://angular.dev/api/forms/Validators): required uses emptiness, regex input retains its matching semantics. +- [FormGroupDirective source](https://github.com/angular/angular/blob/main/packages/forms/src/directives/reactive_directives/form_group_directive.ts): submit forwarding. Installed Angular 22 implementation checked for default prevention on ordinary forms; method=dialog is outside this topic's scope. + +Examples are local form previews, not the learner exercise or an HTTP implementation. Only the distinction between field state and request state is noted; API request lifecycle implementation and success-message dismissal remain outside this topic. Supported-attribute validation and TypeScript validation are alternatives, not a required pair. No new diagram is needed for this syntax/placement lookup. + +Verification: the exact paired snippets pass strict Angular template compilation in a scratch workspace. Agent-run TestBed checks confirm model required/nonblank/maxlength validation, submit default prevention and rendered result, and equivalent rules attached through template attributes with no model validators. No learner exercise files are changed. + +- [Template variables](https://angular.dev/guide/templates/variables): template reference variables on native elements expose the element and its value. +- [HTML Standard — form](https://html.spec.whatwg.org/multipage/forms.html#the-form-element): native submission and validation semantics. +- [NgForm](https://angular.dev/api/forms/NgForm): FormsModule attaches NgForm to ordinary forms; ngNoForm opts out. + +The native lookup fragment is compiled separately with no Angular forms imports and a stub load(id) handler; agent-run TestBed checks confirm passing the input text, required-field blocking on button submission and default prevention. It is illustrative and does not change ProductsPage. + +Revision 2026-11-02: submission behavior and field-state tracking are complementary decisions. Replaced the dictionary table with the exact FormGroup/template-control wiring, moved the paired reactive example earlier, and consolidated native/Angular submission guidance. ngNoForm excludes both NgForm attachment and NgNoValidate; either forms module otherwise exports the shared no-validation directive. ngNativeValidate preserves native validation while retaining Angular form submission. + +- [Native and Angular validation](https://angular.dev/guide/forms/form-validation#interaction-with-native-html-form-validation): Angular normally adds novalidate; ngNativeValidate opts into browser validation. +- Installed Angular 22 forms source (NgForm, NgNoValidate and forms-module exports) checked for selector exclusions and shared directive availability. Native example verified with no forms import and with each forms module in scope, including required blocking and prevented navigation. + +Verification 2026-11-02: exact reactive/native snippets compile with strict Angular templates. Fresh TestBed checks pass for model required/nonblank/maxlength rules, template-only equivalent validators, reactive submit default prevention/result, native ngNoForm submission under no imports/FormsModule/ReactiveFormsModule, and FormsModule ngSubmit plus ngNativeValidate preserving required checks. Desktop tables fit; mobile tables/code scroll within their containers without page overflow. + +- [Springdoc introduction](https://springdoc.org/intro.html): exports supported Bean Validation annotations, including NotNull/Min/Max/Size, to OpenAPI metadata. The shared-rule note describes an optional schema-to-Angular-validator generator/adapter, not a built-in Angular feature or a guarantee that generated client types enforce runtime rules. Detailed tooling and implementation remain outside this topic. diff --git a/content/topics/angular-forms-validation/topic.md b/content/topics/angular-forms-validation/topic.md new file mode 100644 index 0000000..9b4615d --- /dev/null +++ b/content/topics/angular-forms-validation/topic.md @@ -0,0 +1,132 @@ +--- +id: '8f0eac15-f8c7-4a92-80bb-0c45ff6b4e87' +title: 'Forms and validation' +status: 'accepted' +summary: 'Wire a reactive form, choose where to declare validators, and handle submission without page navigation.' +iconKey: 'operations' +domains: + - 'javascript' +kind: 'operations' +childTopicIds: [] +relatedTopicIds: + - 'f7aa760f-30aa-43da-8746-20a39e39529e' + - '6b2a1c19-acaa-4793-9e8a-7a783564bde5' +--- + +## Choose submission and field state + +| Need | Add | +| -------------------------------------------- | --------------------------------------------- | +| Submit by button or Enter | `
` + submit button | +| Track field values, validity and interaction | `FormControl`; `FormGroup` for related fields | + +**These choices combine:** a `` does not require a `FormGroup`. +Use an `(input)` handler for immediate reactions to typing, with or without a form. + +## Wire a reactive form + +```text +form: FormGroup ↔ [formGroup]="form" +form.controls.sku ↔ formControlName="sku" +``` + +**`sku-form.ts`** + +```typescript +import { Component, signal } from '@angular/core'; +import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'; + +@Component({ + selector: 'app-sku-form', + imports: [ReactiveFormsModule], + templateUrl: './sku-form.html', +}) +export class SkuForm { + protected readonly form = new FormGroup({ + sku: new FormControl('', { + nonNullable: true, + validators: [Validators.required, Validators.maxLength(32), Validators.pattern(/\S/)], + }), + }); + protected readonly submittedSku = signal(''); + + protected submit(): void { + if (this.form.invalid) return; + this.submittedSku.set(this.form.controls.sku.value); + } +} +``` + +**`sku-form.html`** + +```angular + + + + @if (form.controls.sku.touched && form.controls.sku.invalid) { +

Enter a nonblank SKU of at most 32 characters.

+ } + +
+@if (submittedSku()) { +

Submitted {{ submittedSku() }}

+} +``` + +`nonNullable: true` keeps the control typed as `string`; **it is not an empty-input validator**. + +## Choose where validation lives + +| Declare rules in | Rules apply… | Useful for | +| --------------------- | --------------------------------------- | ------------------------------ | +| TypeScript validators | **Without rendering an input** | Custom rules; model-only tests | +| Template attributes | When **attached to an Angular control** | Simple built-in rules | + +**Either can supply supported rules, including with reactive forms.** If both +are present, **all attached validators apply**; neither location overrides the other. + +Keeping HTML attributes can still serve a separate purpose: **`maxlength` limits +typing** and **`required` identifies a required field**, even when the rule also +exists in TypeScript. Bare attributes do not create Angular controls. + +> **Sharing UI/backend rules:** basic field constraints can come from a shared +> schema. Supported Java validation annotations can feed an OpenAPI schema, then a +> generator or adapter can produce Angular validators. **Generated types alone do +> not enforce validation.** + +## Submit without navigation + +- **Angular forms:** use `(ngSubmit)`, without an additional `(submit)` handler or + `preventDefault()`. A submit button and Enter can both trigger submission. +- **Keep the handler guard**, even when the button is disabled. For an API call, + also block duplicate requests: `if (this.form.invalid || this.pending()) return;`. + +**A lookup without Angular controls:** + +```angular +
+ + + +
+``` + +`#productId` references the input; `.value` reads its text. No Angular forms +import is needed. **`ngNoForm` keeps this form native**, even if `FormsModule` or +`ReactiveFormsModule` is imported: the browser enforces `required`, and the +handler prevents navigation. + +> **Angular forms normally disable browser validation.** With reactive controls, +> display errors from control state. To use `(ngSubmit)` without a `FormGroup`, +> import `FormsModule`; add `ngNativeValidate` if relying on browser `required` or +> `pattern` checks. + +## Avoid validation gaps + +- **`required` accepts whitespace-only text.** Add `Validators.pattern(/\S/)` + when spaces alone must be rejected. +- **`step="0.01"` is not an Angular decimal validator.** Add a validator if Angular + form validity must enforce decimal precision. +- **Keep field state separate from request state.** Controls track values and + validity; a request's `pending`/`error` state belongs to the API operation. +- **Validate on the server too.** Client checks can be bypassed. diff --git a/content/topics/angular-http-service/sources.md b/content/topics/angular-http-service/sources.md new file mode 100644 index 0000000..095d399 --- /dev/null +++ b/content/topics/angular-http-service/sources.md @@ -0,0 +1,15 @@ +# Authoring sources + +Retrieval job: recover the DI declaration, typed HTTP call and bounded one-request consumer with pending/error state. Targets Angular 22; verified 2026-10-30. + +- [Injectable API](https://angular.dev/api/core/Injectable): providedIn registration and injectable metadata. +- [Injection context](https://angular.dev/guide/di/dependency-injection-context): inject in Angular-created class fields; ordinary event handlers are not injection contexts. +- [HTTP setup](https://angular.dev/guide/http/setup): HttpClient injectable by default since Angular 21; provideHttpClient configures features. +- [Making requests](https://angular.dev/guide/http/making-requests): subscriptions send requests, each subscription is independent, generics do not validate JSON, and get/post signatures. +- [DestroyRef](https://angular.dev/api/core/DestroyRef): supplied without manual registration; injected in a component, its destruction callbacks follow that component's lifetime. +- [takeUntilDestroyed](https://angular.dev/ecosystem/rxjs-interop/take-until-destroyed): explicit DestroyRef outside injection context and teardown on destruction. +- [RxJS finalize](https://rxjs.dev/api/operators/finalize): completion, error and unsubscribe cleanup. + +Installed Angular common packages 22.2.4 and 22.1.x declare HttpClient providedIn root. Scratch verification checks service injection, request URL/method, successful rendering, HTTP error rendering, pending duplicate suppression and destruction/cancellation; it does not contact the learner's live API. Form validation, retry policy and latest-request-wins lookup are separate concerns; this example suppresses overlapping calls. + +2026-11-01 retrieval revision: move default HttpClient availability before the service example and identify Angular-supplied DestroyRef beside the component example; implementation snippets are unchanged. diff --git a/content/topics/angular-http-service/topic.md b/content/topics/angular-http-service/topic.md new file mode 100644 index 0000000..5b9119c --- /dev/null +++ b/content/topics/angular-http-service/topic.md @@ -0,0 +1,130 @@ +--- +id: '6b2a1c19-acaa-4793-9e8a-7a783564bde5' +title: 'HTTP services and dependency injection' +status: 'accepted' +summary: 'Declare and inject a typed HTTP service, then handle its result, pending state and errors in a component.' +iconKey: 'network' +domains: + - 'javascript' + - 'http' +kind: 'operations' +childTopicIds: [] +relatedTopicIds: + - 'b35c83b3-ae4d-405b-a06c-21bc3d24bfd5' + - '253aba39-8aed-4a85-94fb-7f09406e72d3' +--- + +## Do I need to provide HttpClient? + +**Angular 21+ provides `HttpClient` by default.** Inject it directly for basic +requests. Use `provideHttpClient(...)` in `app.config.ts` to configure features +such as interceptors. Older Angular versions can require explicit HTTP +provisioning. + +## Declare the service + +**`product-service.ts`** + +```typescript +@Injectable({ providedIn: 'root' }) +export class ProductService { + private readonly http = inject(HttpClient); + + getById(id: string): Observable { + const url = `/products/${id}`; + return this.http.get(url); + } +} +``` + +**`product.ts`** + +```typescript +export interface Product { + id: string; + sku: string; + name: string; + price: number; +} +``` + +`providedIn: 'root'` registers the service with the **application root injector**. +Consumers use `inject(ProductService)`; services do **not** go in a component's +template `imports`. + +> **Calling `getById()` creates an Observable; subscribing sends the request.** +> Each subscription to this HTTP Observable sends another request. + +## Consume the result in a component + +The HTTP Observable delivers the response; signals retain **what the template +should display**. + +Angular supplies **`DestroyRef` without manual registration**; here it refers to +the component's lifetime. + +**`product-lookup.ts`** + +```typescript +@Component({ + selector: 'app-product-lookup', + templateUrl: './product-lookup.html', +}) +export class ProductLookup { + private readonly api = inject(ProductService); + private readonly destroyRef = inject(DestroyRef); + protected readonly product = signal(null); + protected readonly pending = signal(false); + protected readonly error = signal(''); + + protected load(id: string): void { + if (this.pending()) return; + this.product.set(null); + this.error.set(''); + this.pending.set(true); + + this.api + .getById(id) + .pipe( + takeUntilDestroyed(this.destroyRef), + finalize(() => this.pending.set(false)), + ) + .subscribe({ + next: (product) => this.product.set(product), + error: () => this.error.set('Product lookup failed.'), + }); + } +} +``` + +**`product-lookup.html`** + +```angular + + + + +@if (pending()) { +

Loading…

+} +@if (error()) { +

{{ error() }}

+} +@if (product(); as found) { +

{{ found.name }}

+} +``` + +`takeUntilDestroyed(this.destroyRef)` unsubscribes when the component is destroyed. +Pass the injected reference because the click handler runs **outside an injection +context**. `finalize()` also clears pending state on error or cancellation. + +## HTTP boundaries + +- **`` does not validate the JSON response.** It supplies the TypeScript + result type; validate untrusted response data when the API boundary requires it. +- **Relative `/products/...` uses the page's origin.** A development proxy or the + production host must route it to the API. See the related proxy topic. + +For creation, the corresponding call is `http.post(url, body)`; +the backend still validates the submitted data. diff --git a/content/topics/angular-provider-scope/sources.md b/content/topics/angular-provider-scope/sources.md new file mode 100644 index 0000000..509673d --- /dev/null +++ b/content/topics/angular-provider-scope/sources.md @@ -0,0 +1,10 @@ +# Authoring sources + +Retrieval job: choose the registration scope that gives the intended consumers a shared or isolated dependency. Targets standalone Angular 22 with a compact NgModule compatibility note; checked 2026-10-31. + +- [Defining dependency providers](https://angular.dev/guide/di/defining-dependency-providers): automatic versus explicit registration, application/component/directive/route locations, and class-provider shorthand. +- [Hierarchical injectors](https://angular.dev/guide/di/hierarchical-dependency-injection): root environment versus component element scope; provider resolution and overrides; component-owned service destruction; providers versus viewProviders; eager and lazy NgModule scopes. +- [Route.providers](https://angular.dev/api/router/Route#providers): environment injector for the route and its children. Registration alone does not promise a fresh instance on every navigation. +- [Injectable](https://angular.dev/api/core/Injectable): @Injectable() allows DI construction; providedIn controls automatic registration. + +The comparison matrix compares only who shares an instance; automatic versus explicit application registration are alternatives within the same scope. A callout exposes local overrides before the syntax sections. Small code examples carry registration syntax; no additional diagram is needed to repeat those mappings. Provider recipes and advanced/custom injector APIs are outside this retrieval job. Empty service/component bodies are scaffolding for syntax examples, not changes to the learner's product exercise. diff --git a/content/topics/angular-provider-scope/topic.md b/content/topics/angular-provider-scope/topic.md new file mode 100644 index 0000000..9b28cb0 --- /dev/null +++ b/content/topics/angular-provider-scope/topic.md @@ -0,0 +1,99 @@ +--- +id: 'fe994f41-dbc9-456c-b50e-53d3a4a9719c' +title: 'Choose where to provide a dependency' +status: 'accepted' +summary: 'Choose application, route or component scope and recognize when a provider creates a separate service instance.' +iconKey: 'tradeoff' +domains: + - 'javascript' +kind: 'decision-aid' +childTopicIds: [] +relatedTopicIds: + - '64c227ae-34fd-4c0d-bd8d-668c56205fc1' + - '6b2a1c19-acaa-4793-9e8a-7a783564bde5' +--- + +## Choose who should share the dependency + +| Scope | Who shares one instance | +| ----------- | ----------------------- | +| Application | Across the app | +| Route | Route + child routes | +| Component | Component + children | + +> **A more local provider takes precedence.** Registering the same service class +> at component level gives that component subtree its own instance; consumers +> outside that subtree continue using the root registration. + +## Register an application-wide service + +**Automatic registration** — on the service: + +```typescript +@Injectable({ providedIn: 'root' }) +export class ProductService {} +``` + +**Explicit registration** — omit `providedIn` and register in application config: + +```typescript +@Injectable() +export class ProductService {} + +export const appConfig: ApplicationConfig = { + providers: [ProductService], +}; +``` + +These are alternatives; **no extra registration is needed** for a service +already provided at root. Bootstrap options can also be supplied directly to +`bootstrapApplication(App, { providers: [...] })`. + +> **Application root ≠ root component.** `providedIn: 'root'` and application +> configuration use application scope; `App`'s component `providers` use component +> scope. + +## Share within a routed feature + +```typescript +export const routes: Routes = [ + { + path: 'products', + component: ProductsPage, + providers: [ProductDraftState], + }, +]; +``` + +The route and its child routes can use this registration. **Route scope does +not mean a fresh instance on every navigation**; route reuse and injector +lifecycle affect how long it is retained. + +## Give each component its own instance + +```typescript +@Component({ + selector: 'app-product-editor', + template: '', + providers: [ProductService], +}) +export class ProductEditor {} +``` + +This editor uses a **local `ProductService` instance**, even when the service +has `providedIn: 'root'`. Its children can share that instance; a second editor +gets a separate one. Angular destroys the local service when its component is +destroyed. + +Use `viewProviders` instead of `providers` when projected content +(``) should not see the component's local registration. + +## Directive and module registrations + +- **Directive:** `@Directive({ providers: [...] })` registers on the element + hosting the directive. That element is the starting point for local lookup. +- **NgModule:** `@NgModule({ providers: [...] })` supports module-based apps. + Eager modules generally share application scope; lazy modules can have a child + scope. + +`ProductDraftState` and `ProductsPage` represent your own service and component. diff --git a/content/topics/angular-signals-observables/sources.md b/content/topics/angular-signals-observables/sources.md new file mode 100644 index 0000000..4bb8e52 --- /dev/null +++ b/content/topics/angular-signals-observables/sources.md @@ -0,0 +1,35 @@ +# Authoring sources + +Retrieval job: choose async, toSignal or writable signals by how the reader consumes and changes a value, and distinguish the underlying abstractions. Targets Angular 22 and RxJS; checked 2026-11-02. This is a decision aid, not a complete reactive programming guide. + +- [Angular signals](https://angular.dev/guide/signals): current values, tracked template reads, writable state and computed derivations. No independent next/error/complete notification API is exposed by signals; this does not mean a signal getter can never throw. +- [RxJS Observable guide source](https://github.com/ReactiveX/rxjs/blob/master/apps/rxjs.dev/content/guide/observable.md): notifications, subscription, synchronous/asynchronous emission and completion/error semantics. Observable is not a synonym for asynchronous work; stateful Observable sources also exist. +- [Angular HTTP requests](https://angular.dev/guide/http/making-requests): subscription starts a request; the response may feed component state. Re-reading a separately stored signal does not subscribe again. +- [Angular RxJS interop](https://angular.dev/ecosystem/rxjs-interop): toSignal exposes the latest Observable value as a read-only signal usable in TypeScript and computed derivations. The ownership comparison contrasts read-only conversion with explicit subscription into writable state. Basic conversion syntax and destruction cleanup are shown; request-error handling is intentionally omitted from the labeled component fragments. +- [Angular AsyncPipe](https://angular.dev/api/common/AsyncPipe): template consumption of the latest emitted value, with automatic subscription cleanup. + +The matrix compares the abstractions, while the text flow shows the product exercise's boundary between a response and retained state. It is intentionally a compact text flow, not an additional SVG repeating those labels. The two related operational topics retain their implementation snippets. No exercise code is changed and no learner proficiency is inferred from this agent-authored reference. + +- [Angular takeUntilDestroyed](https://angular.dev/ecosystem/rxjs-interop/take-until-destroyed): automatic subscription cleanup using an explicit DestroyRef when subscribing in ngOnInit. + +- [Angular unhandled errors](https://angular.dev/best-practices/error-handling): AsyncPipe forwards unhandled errors to the root ErrorHandler; expected HTTP failures should become operation-specific feedback. +- [Angular ErrorHandler](https://angular.dev/api/core/ErrorHandler): default behavior logs errors to the console. +- [RxJS catchError](https://rxjs.dev/api/operators/catchError): replaces an error with a replacement Observable. The example emits an explicit error state rather than disguising failure as a successful empty list. + +The async error example uses a stable field and one template subscription. It covers one-shot success/failure feedback, not loading state, refresh or retry orchestration. Initial failure without handling leaves AsyncPipe's initial null value; an error after prior emissions does not imply clearing the previous value. + +The opening decision table replaces the earlier UI-state/request-flow split, since both abstractions can represent displayed data. The conceptual matrix is secondary and no longer includes a prescriptive Use for row. + +The toSignal example combines fetched products with a writable local search signal through computed. Both dependencies update the filtered result; it is not a claim that filtering requires signals or cannot be expressed with RxJS. + +- [RxJS 7.8.2 BehaviorSubject](https://github.com/ReactiveX/rxjs/blob/7.8.2/src/internal/BehaviorSubject.ts): retains a current value, emits it to active new subscribers and exposes value/getValue access. +- [RxJS 7.8.2 ReplaySubject](https://github.com/ReactiveX/rxjs/blob/7.8.2/src/internal/ReplaySubject.ts): configurable value/time buffer replayed to new subscribers; not the same getter API as BehaviorSubject. + +The conceptual comparison omits the former Represents row to avoid implying that Observables cannot represent current state. The Consume row distinguishes the general APIs; the short note identifies stateful Observable sources. Route snapshots are a separate Angular API and are not needed for this comparison. + +- [RxJS switchMap 7.8.2](https://github.com/ReactiveX/rxjs/blob/7.8.2/src/internal/operators/switchMap.ts): new source values unsubscribe the previous inner subscription; mergeMap does not implement this replacement behavior. +- [RxJS debounceTime 7.8.2](https://github.com/ReactiveX/rxjs/blob/7.8.2/src/internal/operators/debounceTime.ts): waits for the due time without another source emission. +- [RxJS retry 7.8.2](https://github.com/ReactiveX/rxjs/blob/7.8.2/src/internal/operators/retry.ts): resubscription after failure. +- [Angular HTTP Observable cancellation](https://angular.dev/guide/http/making-requests#http-observables): unsubscribing aborts an in-progress HttpClient request; separate from guaranteed server cancellation or transaction rollback. + +Cancellation wording is scoped to a direct HttpClient subscription. General Observable cleanup is source-dependent; a shared source may continue for other subscribers. No claim is made that aborting HTTP guarantees server rollback or stops an already-started operation. diff --git a/content/topics/angular-signals-observables/topic.md b/content/topics/angular-signals-observables/topic.md new file mode 100644 index 0000000..57dd17d --- /dev/null +++ b/content/topics/angular-signals-observables/topic.md @@ -0,0 +1,137 @@ +--- +id: '253aba39-8aed-4a85-94fb-7f09406e72d3' +title: 'Signals and Observables' +status: 'accepted' +summary: 'Choose async, toSignal or writable signals by how you consume and change a value; compare signals and Observables.' +iconKey: 'tradeoff' +domains: + - 'javascript' +kind: 'decision-aid' +childTopicIds: [] +relatedTopicIds: + - 'f7aa760f-30aa-43da-8746-20a39e39529e' + - '6b2a1c19-acaa-4793-9e8a-7a783564bde5' +--- + +## Choose how to consume and change a value + +**Both signals and Observables can supply data displayed in the UI.** + +| What you want | Starting point | +| ------------------------------------------------- | ------------------- | +| **Display values** supplied by an Observable | `async` pipe | +| Combine Observable results **with other signals** | `toSignal()` | +| Keep a value your component **changes directly** | Writable `signal()` | + +## Compare the abstractions + +| | Signal | Observable | +| --------- | -------------------------- | ------------------------------ | +| Consume | `state()` | `subscribe()` or `async` | +| Derive | `computed(...)` | `map(...)` and other operators | +| End/error | No completion/error events | Can complete or error | + +> **Observables can hold state too:** `BehaviorSubject` retains a current value; +> `ReplaySubject` can replay buffered values to new subscribers. + +**RxJS operators:** + +- `debounceTime` — wait for a pause in input. +- `switchMap` — keep the latest request; unsubscribe from the previous one. +- `retry` — retry failed requests. + +Unsubscribing stops delivery to **that subscriber**. For a direct Angular +`HttpClient` request, it also **aborts the in-flight request**. +**Server work is not rolled back:** the operation may already have completed or +may continue on the server. For other Observable sources, stopping the underlying +work depends on their cleanup behavior. + +> **An Observable does not necessarily emit asynchronously.** For example, +> `of(42)` emits immediately when subscribed to. + +## Combine them for the product list + +```text +HTTP Observable + ↓ response +products.set(response) + ↓ stored state +Template reads products() +``` + +The HTTP request starts when subscribed. Each emitted value is passed to +`products.set(...)`. **Reading `products()` returns the stored value; it does not +send another request.** + +## Follow a source or change the stored value + +**Combine fetched products with a local search signal:** + +```ts +products = toSignal(this.api.getAll(), { initialValue: [] }); +search = signal(''); + +filteredProducts = computed(() => { + const search = this.search(); + return this.products().filter((p) => p.name.includes(search)); +}); +``` + +The filtered list recalculates when **products or search changes**; +the template reads `filteredProducts()`. Useful when the component already uses signals. + +**Store the response — writable signal:** + +```ts +products = signal([]); +private readonly destroyRef = inject(DestroyRef); + +ngOnInit(): void { + this.api.getAll() + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(products => this.products.set(products)); +} + +// After a successful deletion, change the displayed list locally: +removeFromList(id: string): void { + this.products.update(products => products.filter(p => p.id !== id)); +} +``` + +`toSignal()` manages destruction cleanup automatically; the manual subscription +above uses `takeUntilDestroyed`. + +> **`toSignal()` follows the source; a writable signal lets you change the stored state yourself.** +> A plain variable does not provide signal dependency tracking. + +## Show request errors with `async` + +**Unhandled error → `ErrorHandler`** (console logging by default). +The pipe **does not display an error message or retry**. If the first request +fails before emitting, its value remains `null`. + +Use `catchError` to **emit an error state the template can display**: + +```ts +readonly productsState$ = this.api.getAll().pipe( + map(products => ({ products, error: '' })), + catchError(() => of({ products: [], error: 'Failed to load products.' })), +); +``` + +```angular-html +@if (productsState$ | async; as state) { + @if (state.error) { +

{{ state.error }}

+ } @else { + @for (product of state.products; track product.id) { +

{{ product.name }}

+ } + } +} +``` + +**Create the request Observable once in a component property.** Calling +`api.getAll()` inside the template creates a new Observable each time the +expression is evaluated, which can cause `async` to **resubscribe and send repeated +requests**. diff --git a/content/topics/angular/topic.md b/content/topics/angular/topic.md new file mode 100644 index 0000000..747ab34 --- /dev/null +++ b/content/topics/angular/topic.md @@ -0,0 +1,15 @@ +--- +id: 'cbbb9857-d3fa-47b8-8b47-d91b3f3dde7f' +title: 'Angular' +status: 'accepted' +summary: 'Application setup, components, reactive state, services and HTTP integration.' +iconKey: 'architecture' +domains: + - 'javascript' +kind: 'area' +childTopicIds: + - 'd48436d1-d79b-4e9a-bac5-9ff8672920f7' + - '5dd196fa-28a4-4a60-9aaf-26553d7067ec' + - 'b35c83b3-ae4d-405b-a06c-21bc3d24bfd5' +relatedTopicIds: [] +--- diff --git a/content/topics/javascript/topic.md b/content/topics/javascript/topic.md new file mode 100644 index 0000000..57bcaee --- /dev/null +++ b/content/topics/javascript/topic.md @@ -0,0 +1,15 @@ +--- +id: '32ce80fd-fd5a-4dce-bcb9-b104889a47da' +title: 'JavaScript' +status: 'accepted' +summary: 'Angular application reference topics.' +iconKey: 'javascript' +domains: + - 'javascript' +kind: 'area' +childTopicIds: + - 'cbbb9857-d3fa-47b8-8b47-d91b3f3dde7f' +relatedTopicIds: [] +--- + +Reference topics for Angular applications. diff --git a/contracts/runtime-catalog.ts b/contracts/runtime-catalog.ts index a500d72..0f36a12 100644 --- a/contracts/runtime-catalog.ts +++ b/contracts/runtime-catalog.ts @@ -1,5 +1,6 @@ export const TOPIC_ICON_KEYS = [ 'java', + 'javascript', 'architecture', 'algorithm', 'database', @@ -22,6 +23,7 @@ export const TOPIC_ICON_KEYS = [ 'ordering', 'persistence', 'network', + 'tradeoff', 'validation', ] as const; @@ -36,6 +38,7 @@ export const TOPIC_DOMAIN_KEYS = [ 'http', 'system-design', 'algorithms-data-structures', + 'javascript', ] as const; export type TopicDomainKey = (typeof TOPIC_DOMAIN_KEYS)[number]; @@ -49,6 +52,7 @@ export const TOPIC_DOMAIN_LABELS: Readonly> = { http: 'HTTP', 'system-design': 'System Design', 'algorithms-data-structures': 'Algorithms and data structures', + javascript: 'JavaScript', }; export const TOPIC_KIND_KEYS = [ diff --git a/docs/content-model.md b/docs/content-model.md index 1b59cc5..69452aa 100644 --- a/docs/content-model.md +++ b/docs/content-model.md @@ -131,6 +131,7 @@ published corpus: | `http` | HTTP | HTTP protocol semantics and lookup references | | `system-design` | System Design | Architecture decisions, estimation, and design exercises | | `algorithms-data-structures` | Algorithms and data structures | Complexity, algorithms, and language-independent data-structure concepts | +| `javascript` | JavaScript | JavaScript and Angular application development | These keys are a closed contract rather than author-defined tags. A Topic can belong to several domains, such as Java and Collections or Persistence and diff --git a/docs/content-storage.md b/docs/content-storage.md index 0847563..ab76ac7 100644 --- a/docs/content-storage.md +++ b/docs/content-storage.md @@ -141,10 +141,10 @@ Two presentation properties are optional for a Topic generally: registry key rather than a filename, URL, or markup fragment. When omitted, the UI supplies its generic icon fallback. -The supported icon keys are `java`, `architecture`, `algorithm`, `database`, +The supported icon keys are `java`, `javascript`, `architecture`, `algorithm`, `database`, `array`, `collection`, `conversion`, `copy`, `creation`, `deque`, `heap`, `list`, `map`, `operations`, `priority`, `queue`, `set`, `complexity`, `concurrency`, -`equality`, `ordering`, `persistence`, `network`, and `validation`. Topics may +`equality`, `ordering`, `persistence`, `network`, `tradeoff`, and `validation`. Topics may reuse a key. Extending this closed vocabulary is a deliberate shared-contract change rather than an ordinary content edit. @@ -153,6 +153,7 @@ The subject-specific keys provide distinct recognition within a technical domain | Key | Symbol | Typical subject | | --- | --- | --- | | `network` | Connected components | System architecture | +| `tradeoff` | Balance scales | Trade-off decisions | | `validation` | Checklist | Validation rules | These assets use the selected Lucide 1.17.0 glyphs with the application's stroke @@ -162,7 +163,7 @@ runtime icon-library dependency. The supported domain keys, in canonical generated and display order, are `java`, `collections`, `concurrency`, `persistence`, `databases`, `http`, -`system-design`, and `algorithms-data-structures`. Source membership order is +`system-design`, `algorithms-data-structures`, and `javascript`. Source membership order is not meaningful; generation normalizes it to this shared order. Every Topic has at least one domain and cannot repeat a domain key. @@ -376,7 +377,8 @@ Its conceptual shape is: "databases": [], "http": [], "system-design": [], - "algorithms-data-structures": [] + "algorithms-data-structures": [], + "javascript": [] }, "topicIdsByKind": { "area": ["11111111-1111-4111-8111-111111111111"], diff --git a/e2e/app.spec.ts b/e2e/app.spec.ts index 2c9dc90..87100a0 100644 --- a/e2e/app.spec.ts +++ b/e2e/app.spec.ts @@ -17,11 +17,11 @@ test.describe('cross-browser smoke', { tag: '@smoke' }, () => { await expect(page.locator('main').getByRole('search')).toHaveCount(0); await expect(page.getByRole('link', { name: 'All topics' })).toHaveAttribute('href', '/topics'); await expect(page.getByRole('navigation', { name: 'Domains' }).getByRole('link')).toHaveCount( - 8, + 9, ); await expect( page.getByRole('navigation', { name: 'Domains' }).getByRole('link', { - name: /^Java/u, + name: /^Java\b/u, }), ).toHaveAttribute('href', '/topics?domain=java'); await expect( diff --git a/public/icons/topics/javascript.svg b/public/icons/topics/javascript.svg new file mode 100644 index 0000000..5925ba4 --- /dev/null +++ b/public/icons/topics/javascript.svg @@ -0,0 +1,16 @@ + + + + + JS + + + diff --git a/public/icons/topics/tradeoff.svg b/public/icons/topics/tradeoff.svg new file mode 100644 index 0000000..b7b7212 --- /dev/null +++ b/public/icons/topics/tradeoff.svg @@ -0,0 +1,20 @@ + + + + + + + + + diff --git a/src/app/app.routes.spec.ts b/src/app/app.routes.spec.ts index f35599b..1f02ffa 100644 --- a/src/app/app.routes.spec.ts +++ b/src/app/app.routes.spec.ts @@ -32,7 +32,7 @@ describe('application routes', () => { ); expect(routeElement?.querySelector('form[role="search"]')).toBeNull(); - expect(routeElement?.querySelectorAll('nav[aria-label="Domains"] a')).toHaveLength(8); + expect(routeElement?.querySelectorAll('nav[aria-label="Domains"] a')).toHaveLength(9); expect(topicLink?.textContent).toContain('Java'); expect(topicLink?.textContent).toContain( 'Core language, collections, concurrency, and persistence concepts.', @@ -53,7 +53,7 @@ describe('application routes', () => { routeElement?.querySelectorAll( '.domain-hierarchy__root > .domain-hierarchy__item > .domain-hierarchy__link', ), - ).toHaveLength(5); + ).toHaveLength(6); expect(TestBed.inject(Router).url).toBe('/topics'); expect(TestBed.inject(Title).getTitle()).toBe('All topics | Engineering Reference'); }); diff --git a/src/app/browse/topic-index-page.spec.ts b/src/app/browse/topic-index-page.spec.ts index 6afe1a9..f29bf1f 100644 --- a/src/app/browse/topic-index-page.spec.ts +++ b/src/app/browse/topic-index-page.spec.ts @@ -11,7 +11,7 @@ describe('TopicIndexPage', () => { }); }); - it('renders the unconstrained catalog as five expanded root trees', async () => { + it('renders the unconstrained catalog as expanded root trees', async () => { const harness = await RouterTestingHarness.create(); await harness.navigateByUrl('/topics', TopicIndexPage); await harness.fixture.whenStable(); @@ -21,14 +21,14 @@ describe('TopicIndexPage', () => { Array.from(host.querySelectorAll('.domain-hierarchy__root > .domain-hierarchy__item')).map( (item) => item.querySelector('.domain-hierarchy__title')?.textContent?.trim(), ), - ).toEqual(['Java', 'System Design', 'HTTP', 'Databases', 'Idempotency keys']); + ).toEqual(['Java', 'System Design', 'HTTP', 'Databases', 'Idempotency keys', 'JavaScript']); expect( Array.from( host.querySelectorAll( '.domain-hierarchy__root > .domain-hierarchy__item > button', ), ).map((button) => button.getAttribute('aria-expanded')), - ).toEqual(['true', 'true', 'true', 'true', 'true']); + ).toEqual(['true', 'true', 'true', 'true', 'true', 'true']); for (const disclosure of host.querySelectorAll( '.domain-hierarchy__disclosure', )) { @@ -38,8 +38,8 @@ describe('TopicIndexPage', () => { Array.from( host.querySelectorAll('.domain-hierarchy__root > .domain-hierarchy__item app-topic-icon'), ).map((icon) => icon.getAttribute('data-icon-key')), - ).toEqual(['java', 'architecture', 'architecture', 'database', 'architecture']); - expect(host.querySelector('[role="status"]')?.textContent).toContain('110 topics'); + ).toEqual(['java', 'architecture', 'architecture', 'database', 'architecture', 'javascript']); + expect(host.querySelector('[role="status"]')?.textContent).toContain('122 topics'); }); it('renders the default System Design view as an expandable hierarchy', async () => { diff --git a/src/app/catalog/catalog.service.spec.ts b/src/app/catalog/catalog.service.spec.ts index 399c002..7f62fe4 100644 --- a/src/app/catalog/catalog.service.spec.ts +++ b/src/app/catalog/catalog.service.spec.ts @@ -103,9 +103,10 @@ describe('CatalogService', () => { 'http', 'system-design', 'algorithms-data-structures', + 'javascript', ]); expect(service.getDomainTopicCount('system-design')).toBe(37); - expect(service.getDomainTopicCount('http')).toBe(18); + expect(service.getDomainTopicCount('http')).toBe(20); expect(service.getKindOptions().map(({ key }) => key)).toEqual([ 'area', 'concept', @@ -218,7 +219,7 @@ describe('CatalogService', () => { const view = service.getTopicBrowseView({ query: '', domain: null, kind: null, status: null }); expect(view.mode).toBe('hierarchy'); - expect(view.resultCount).toBe(110); + expect(view.resultCount).toBe(122); expect(view.sections).toEqual([]); expect(view.hierarchyRoots.map(({ title }) => title)).toEqual([ 'Java', @@ -226,6 +227,7 @@ describe('CatalogService', () => { 'HTTP', 'Databases', 'Idempotency keys', + 'JavaScript', ]); }); @@ -302,6 +304,7 @@ describe('CatalogService', () => { 'System Design', 'HTTP', 'Idempotency keys', + 'JavaScript', ]); expect(view.hierarchyRoots[0].matchesDomain).toBe(false); expect(view.hierarchyRoots[0].children.map(({ title }) => title)).toEqual([ @@ -487,6 +490,7 @@ describe('CatalogService', () => { 'HTTP', 'Databases', 'Idempotency keys', + 'JavaScript', ]); }); diff --git a/src/app/landing/landing-page.ts b/src/app/landing/landing-page.ts index f7b5b40..f7609c7 100644 --- a/src/app/landing/landing-page.ts +++ b/src/app/landing/landing-page.ts @@ -17,6 +17,7 @@ const DOMAIN_PRESENTATION: Readonly< http: { icon: 'http', tone: 'neutral' }, 'system-design': { icon: 'architecture', tone: 'forest' }, 'algorithms-data-structures': { icon: 'algorithm', tone: 'ochre' }, + javascript: { icon: 'javascript', tone: 'ochre' }, }; @Component({ diff --git a/src/app/ui/topic-icon/topic-icon.css b/src/app/ui/topic-icon/topic-icon.css index 9e9cd8d..36c5f6f 100644 --- a/src/app/ui/topic-icon/topic-icon.css +++ b/src/app/ui/topic-icon/topic-icon.css @@ -26,8 +26,10 @@ img { --topic-icon-color: var(--color-accent-forest); } +:host([data-icon-key='javascript']), :host([data-icon-key='algorithm']), -:host([data-icon-key='complexity']) { +:host([data-icon-key='complexity']), +:host([data-icon-key='tradeoff']) { --topic-icon-background: var(--color-accent-ochre-soft); --topic-icon-color: var(--color-accent-ochre); } diff --git a/tools/content/generate.spec.ts b/tools/content/generate.spec.ts index f780acb..3704849 100644 --- a/tools/content/generate.spec.ts +++ b/tools/content/generate.spec.ts @@ -275,6 +275,7 @@ describe('generateContent', () => { http: [], 'system-design': [], 'algorithms-data-structures': [complexityTopicId, queueTopicId], + javascript: [], }); expect(parsedCatalog.topicIdsByKind).toEqual({ area: [javaTopicId], diff --git a/tools/content/runtime-catalog.spec.ts b/tools/content/runtime-catalog.spec.ts index e5d4ab7..59c38cc 100644 --- a/tools/content/runtime-catalog.spec.ts +++ b/tools/content/runtime-catalog.spec.ts @@ -17,6 +17,7 @@ describe('runtime catalog vocabularies', () => { 'http', 'system-design', 'algorithms-data-structures', + 'javascript', ]); expect(TOPIC_DOMAIN_KEYS.map((key) => TOPIC_DOMAIN_LABELS[key])).toEqual([ 'Java', @@ -27,6 +28,7 @@ describe('runtime catalog vocabularies', () => { 'HTTP', 'System Design', 'Algorithms and data structures', + 'JavaScript', ]); });