@anglr/select 16.0.3 → 16.0.4-beta.20260511085948
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/angular-developer/SKILL.md +130 -0
- package/.claude/skills/angular-developer/references/angular-animations.md +160 -0
- package/.claude/skills/angular-developer/references/angular-aria.md +410 -0
- package/.claude/skills/angular-developer/references/cli.md +86 -0
- package/.claude/skills/angular-developer/references/component-harnesses.md +59 -0
- package/.claude/skills/angular-developer/references/component-styling.md +91 -0
- package/.claude/skills/angular-developer/references/components.md +117 -0
- package/.claude/skills/angular-developer/references/creating-services.md +97 -0
- package/.claude/skills/angular-developer/references/data-resolvers.md +69 -0
- package/.claude/skills/angular-developer/references/define-routes.md +67 -0
- package/.claude/skills/angular-developer/references/defining-providers.md +72 -0
- package/.claude/skills/angular-developer/references/di-fundamentals.md +120 -0
- package/.claude/skills/angular-developer/references/e2e-testing.md +66 -0
- package/.claude/skills/angular-developer/references/effects.md +83 -0
- package/.claude/skills/angular-developer/references/hierarchical-injectors.md +43 -0
- package/.claude/skills/angular-developer/references/host-elements.md +80 -0
- package/.claude/skills/angular-developer/references/injection-context.md +63 -0
- package/.claude/skills/angular-developer/references/inputs.md +101 -0
- package/.claude/skills/angular-developer/references/linked-signal.md +59 -0
- package/.claude/skills/angular-developer/references/loading-strategies.md +61 -0
- package/.claude/skills/angular-developer/references/mcp.md +106 -0
- package/.claude/skills/angular-developer/references/migrations.md +30 -0
- package/.claude/skills/angular-developer/references/navigate-to-routes.md +69 -0
- package/.claude/skills/angular-developer/references/outputs.md +86 -0
- package/.claude/skills/angular-developer/references/reactive-forms.md +122 -0
- package/.claude/skills/angular-developer/references/rendering-strategies.md +44 -0
- package/.claude/skills/angular-developer/references/resource.md +77 -0
- package/.claude/skills/angular-developer/references/route-animations.md +56 -0
- package/.claude/skills/angular-developer/references/route-guards.md +52 -0
- package/.claude/skills/angular-developer/references/router-lifecycle.md +45 -0
- package/.claude/skills/angular-developer/references/router-testing.md +87 -0
- package/.claude/skills/angular-developer/references/show-routes-with-outlets.md +68 -0
- package/.claude/skills/angular-developer/references/signal-forms.md +897 -0
- package/.claude/skills/angular-developer/references/signals-overview.md +94 -0
- package/.claude/skills/angular-developer/references/tailwind-css.md +69 -0
- package/.claude/skills/angular-developer/references/template-driven-forms.md +114 -0
- package/.claude/skills/angular-developer/references/testing-fundamentals.md +66 -0
- package/.github/instructions/typescript/code-conventions.md +8 -0
- package/.github/instructions/typescript/comments.md +41 -0
- package/.github/instructions/typescript/formatting.md +42 -0
- package/.github/instructions/typescript/naming-conventions.md +7 -0
- package/.github/instructions/typescript.instructions.md +26 -0
- package/package.json +1 -1
- package/readme.md +1288 -99
- package/version.bak +1 -1
- package/.github/copilot-instructions.md +0 -1
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# Dependency Injection (DI) Fundamentals
|
|
2
|
+
|
|
3
|
+
Dependency Injection (DI) is a design pattern used to organize and share code across an application by allowing you to "inject" features into different parts. This improves code maintainability, scalability, and testability.
|
|
4
|
+
|
|
5
|
+
## How DI Works in Angular
|
|
6
|
+
|
|
7
|
+
There are two primary ways code interacts with Angular's DI system:
|
|
8
|
+
|
|
9
|
+
1. **Providing**: Making values (objects, functions, primitives) available to the DI system.
|
|
10
|
+
2. **Injecting**: Asking the DI system for those values.
|
|
11
|
+
|
|
12
|
+
Angular components, directives, and services automatically participate in DI.
|
|
13
|
+
|
|
14
|
+
## Services
|
|
15
|
+
|
|
16
|
+
A **service** is the most common way to share data and functionality across an application. It is a TypeScript class decorated with `@Injectable()`.
|
|
17
|
+
|
|
18
|
+
### Creating a Service
|
|
19
|
+
|
|
20
|
+
Use the `providedIn: 'root'` option in the `@Injectable` decorator to make the service a singleton available throughout the entire application. This is the recommended approach for most services.
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import {Injectable} from '@angular/core';
|
|
24
|
+
|
|
25
|
+
@Injectable({
|
|
26
|
+
providedIn: 'root', // Makes this a singleton available everywhere
|
|
27
|
+
})
|
|
28
|
+
export class AnalyticsLogger {
|
|
29
|
+
trackEvent(category: string, value: string) {
|
|
30
|
+
console.log('Analytics event logged:', {category, value});
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Common uses for services include:
|
|
36
|
+
|
|
37
|
+
- Data clients (API calls)
|
|
38
|
+
- State management
|
|
39
|
+
- Authentication and authorization
|
|
40
|
+
- Logging and error handling
|
|
41
|
+
- Utility functions
|
|
42
|
+
|
|
43
|
+
## Injecting Dependencies
|
|
44
|
+
|
|
45
|
+
Use Angular's `inject()` function to request dependencies.
|
|
46
|
+
|
|
47
|
+
### The `inject()` Function
|
|
48
|
+
|
|
49
|
+
You can use the `inject()` function to get an instance of a service (or any other provided token).
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import {Component, inject} from '@angular/core';
|
|
53
|
+
import {Router} from '@angular/router';
|
|
54
|
+
import {AnalyticsLogger} from './analytics-logger.service';
|
|
55
|
+
|
|
56
|
+
@Component({
|
|
57
|
+
selector: 'app-navbar',
|
|
58
|
+
template: `<a href="#" (click)="navigateToDetail($event)">Detail Page</a>`,
|
|
59
|
+
})
|
|
60
|
+
export class Navbar {
|
|
61
|
+
// Injecting dependencies using class field initializers
|
|
62
|
+
private router = inject(Router);
|
|
63
|
+
private analytics = inject(AnalyticsLogger);
|
|
64
|
+
|
|
65
|
+
navigateToDetail(event: Event) {
|
|
66
|
+
event.preventDefault();
|
|
67
|
+
this.analytics.trackEvent('navigation', '/details');
|
|
68
|
+
this.router.navigate(['/details']);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Where can `inject()` be used? (Injection Context)
|
|
74
|
+
|
|
75
|
+
You can call `inject()` in an **injection context**. The most common injection contexts are during the construction of a component, directive, or service.
|
|
76
|
+
|
|
77
|
+
Valid places to call `inject()`:
|
|
78
|
+
|
|
79
|
+
1. **Class field initializers** (Recommended)
|
|
80
|
+
2. **Constructor body**
|
|
81
|
+
3. **Route guards and resolvers** (which are executed in an injection context)
|
|
82
|
+
4. **Factory functions** used in providers
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
import {Component, Directive, Injectable, inject, ElementRef} from '@angular/core';
|
|
86
|
+
import {HttpClient} from '@angular/common/http';
|
|
87
|
+
|
|
88
|
+
// 1. In a Component (Field Initializer & Constructor)
|
|
89
|
+
@Component({
|
|
90
|
+
/*...*/
|
|
91
|
+
})
|
|
92
|
+
export class Example {
|
|
93
|
+
private service1 = inject(MyService); // ✅ Field initializer
|
|
94
|
+
|
|
95
|
+
private service2: MyService;
|
|
96
|
+
constructor() {
|
|
97
|
+
this.service2 = inject(MyService); // ✅ Constructor body
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// 2. In a Directive
|
|
102
|
+
@Directive({
|
|
103
|
+
/*...*/
|
|
104
|
+
})
|
|
105
|
+
export class MyDirective {
|
|
106
|
+
private element = inject(ElementRef); // ✅ Field initializer
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// 3. In a Service
|
|
110
|
+
@Injectable({providedIn: 'root'})
|
|
111
|
+
export class MyService {
|
|
112
|
+
private http = inject(HttpClient); // ✅ Field initializer
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// 4. In a Route Guard (Functional)
|
|
116
|
+
export const authGuard = () => {
|
|
117
|
+
const auth = inject(AuthService); // ✅ Route Guard
|
|
118
|
+
return auth.isAuthenticated();
|
|
119
|
+
};
|
|
120
|
+
```
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# End-to-End (E2E) Testing
|
|
2
|
+
|
|
3
|
+
This project uses [Cypress](https://www.cypress.io/) for end-to-end (E2E) testing, which simulates real user interactions in a browser. The E2E tests are located primarily within the `devtools/` package.
|
|
4
|
+
|
|
5
|
+
## Running E2E Tests
|
|
6
|
+
|
|
7
|
+
The primary way to run E2E tests is through the `pnpm` script defined in the root `package.json`.
|
|
8
|
+
|
|
9
|
+
1. **Build DevTools:** The E2E tests run against a built version of the devtools extension. You must build it first:
|
|
10
|
+
|
|
11
|
+
```shell
|
|
12
|
+
pnpm -F ng-devtools-mcp build:dev
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
2. **Run Cypress:** Use the `cy:open` or `cy:run` script:
|
|
16
|
+
- To open the interactive Cypress Test Runner:
|
|
17
|
+
```shell
|
|
18
|
+
pnpm -F ng-devtools-mcp cy:open
|
|
19
|
+
```
|
|
20
|
+
- To run the tests headlessly in the terminal (ideal for CI):
|
|
21
|
+
```shell
|
|
22
|
+
pnpm -F ng-devtools-mcp cy:run
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Test Structure
|
|
26
|
+
|
|
27
|
+
- **Configuration:** The main Cypress configuration is located at `devtools/cypress.json`.
|
|
28
|
+
- **Specs:** Test files (specs) are located in `devtools/cypress/integration/`.
|
|
29
|
+
- **Custom Commands:** Reusable custom commands and actions are defined in `devtools/cypress/support/`.
|
|
30
|
+
|
|
31
|
+
### Example E2E Test Snippet
|
|
32
|
+
|
|
33
|
+
A typical test might look like this:
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
// in devtools/cypress/integration/profiler.spec.ts
|
|
37
|
+
|
|
38
|
+
describe('Profiler', () => {
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
cy.visit('/?e2e-app');
|
|
41
|
+
cy.wait(1000);
|
|
42
|
+
cy.get('ng-devtools-tabs').find('a').contains('Profiler').click();
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('should record and display profiling data', () => {
|
|
46
|
+
// Find the record button and click it
|
|
47
|
+
cy.get('button[aria-label="start-recording-button"]').click();
|
|
48
|
+
|
|
49
|
+
// Interact with the test application to generate profiling data
|
|
50
|
+
cy.get('body').find('#cards button').first().click();
|
|
51
|
+
cy.wait(500);
|
|
52
|
+
|
|
53
|
+
// Stop recording
|
|
54
|
+
cy.get('button[aria-label="stop-recording-button"]').click();
|
|
55
|
+
|
|
56
|
+
// Assert that the flame graph is now visible
|
|
57
|
+
cy.get('ng-devtools-recording-timeline').find('canvas').should('be.visible');
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### Best Practices
|
|
63
|
+
|
|
64
|
+
- **Use `data-` attributes:** Whenever possible, use `data-cy` or similar attributes for selecting elements to make tests more resilient to CSS or structural changes.
|
|
65
|
+
- **Custom Commands:** Encapsulate common sequences of actions into custom commands in the `support` directory to keep tests clean and readable.
|
|
66
|
+
- **Wait for Application State:** Use `cy.wait()` for arbitrary waits sparingly. Prefer to wait for specific UI elements to appear or for network requests to complete to avoid flaky tests.
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Side Effects with `effect` and `afterRenderEffect`
|
|
2
|
+
|
|
3
|
+
In Angular, an **effect** is an operation that runs whenever one or more signal values it tracks change.
|
|
4
|
+
|
|
5
|
+
## When to use `effect`
|
|
6
|
+
|
|
7
|
+
Effects are intended for syncing signal state to imperative, non-signal APIs.
|
|
8
|
+
|
|
9
|
+
**Valid Use Cases:**
|
|
10
|
+
|
|
11
|
+
- Logging analytics.
|
|
12
|
+
- Syncing state to `localStorage` or `sessionStorage`.
|
|
13
|
+
- Performing custom rendering to a `<canvas>` or 3rd-party charting library.
|
|
14
|
+
|
|
15
|
+
**CRITICAL RULE: DO NOT use effects to propagate state.**
|
|
16
|
+
If you find yourself using `.set()` or `.update()` on a signal _inside_ an effect to keep two signals in sync, you are making a mistake. This causes `ExpressionChangedAfterItHasBeenChecked` errors and infinite loops. **Always use `computed()` or `linkedSignal()` for state derivation.**
|
|
17
|
+
|
|
18
|
+
## Basic Usage
|
|
19
|
+
|
|
20
|
+
Effects execute asynchronously during the change detection process. They always run at least once.
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { Component, signal, effect } from '@angular/core';
|
|
24
|
+
|
|
25
|
+
@Component({...})
|
|
26
|
+
export class Example {
|
|
27
|
+
count = signal(0);
|
|
28
|
+
|
|
29
|
+
constructor() {
|
|
30
|
+
// Effect must be created in an injection context (e.g., a constructor)
|
|
31
|
+
effect((onCleanup) => {
|
|
32
|
+
console.log(`Count changed to ${this.count()}`);
|
|
33
|
+
|
|
34
|
+
const timer = setTimeout(() => console.log('Timer finished'), 1000);
|
|
35
|
+
|
|
36
|
+
// Cleanup function runs before the next execution, or when destroyed
|
|
37
|
+
onCleanup(() => clearTimeout(timer));
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## DOM Manipulation with `afterRenderEffect`
|
|
44
|
+
|
|
45
|
+
Standard `effect` runs _before_ Angular updates the DOM. If you need to manually inspect or modify the DOM based on a signal change (e.g., integrating a 3rd party UI library), use `afterRenderEffect`.
|
|
46
|
+
|
|
47
|
+
`afterRenderEffect` runs after Angular has finished rendering the DOM.
|
|
48
|
+
|
|
49
|
+
### Render Phases
|
|
50
|
+
|
|
51
|
+
To prevent reflows (forced layout thrashing), `afterRenderEffect` forces you to divide your DOM reads and writes into specific phases.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
import { Component, afterRenderEffect, viewChild, ElementRef } from '@angular/core';
|
|
55
|
+
|
|
56
|
+
@Component({...})
|
|
57
|
+
export class Chart {
|
|
58
|
+
canvas = viewChild.required<ElementRef>('canvas');
|
|
59
|
+
|
|
60
|
+
constructor() {
|
|
61
|
+
afterRenderEffect({
|
|
62
|
+
// 1. Read from the DOM
|
|
63
|
+
earlyRead: () => {
|
|
64
|
+
return this.canvas().nativeElement.getBoundingClientRect().width;
|
|
65
|
+
},
|
|
66
|
+
// 2. Write to the DOM (receives the result of the previous phase)
|
|
67
|
+
write: (width) => {
|
|
68
|
+
// NEVER read from the DOM in the write phase.
|
|
69
|
+
setupChart(this.canvas().nativeElement, width);
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
**Available Phases (executed in this order):**
|
|
77
|
+
|
|
78
|
+
1. `earlyRead`
|
|
79
|
+
2. `write` (Never read here)
|
|
80
|
+
3. `mixedReadWrite` (Avoid if possible)
|
|
81
|
+
4. `read` (Never write here)
|
|
82
|
+
|
|
83
|
+
_Note: `afterRenderEffect` only runs on the client, never during Server-Side Rendering (SSR)._
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Hierarchical Injectors
|
|
2
|
+
|
|
3
|
+
Angular's dependency injection system is hierarchical, meaning services can be scoped to different levels of the application.
|
|
4
|
+
|
|
5
|
+
## Types of Injector Hierarchies
|
|
6
|
+
|
|
7
|
+
1. **`EnvironmentInjector` Hierarchy**: Configured via `@Injectable({ providedIn: 'root' })` or `ApplicationConfig.providers` during bootstrap. These are global singletons.
|
|
8
|
+
2. **`ElementInjector` Hierarchy**: Created implicitly at each DOM element. Configured via the `providers` or `viewProviders` array in `@Component()` or `@Directive()`.
|
|
9
|
+
|
|
10
|
+
## Resolution Rules
|
|
11
|
+
|
|
12
|
+
When a dependency is requested, Angular resolves it in two phases:
|
|
13
|
+
|
|
14
|
+
1. It searches up the **`ElementInjector`** tree, starting from the requesting component/directive up to the root element.
|
|
15
|
+
2. If not found, it searches the **`EnvironmentInjector`** tree, starting from the closest environment injector up to the root.
|
|
16
|
+
3. If still not found, it throws an error (unless marked optional).
|
|
17
|
+
|
|
18
|
+
## Resolution Modifiers
|
|
19
|
+
|
|
20
|
+
You can alter how Angular searches for a dependency using the options object in `inject()`:
|
|
21
|
+
|
|
22
|
+
- **`optional`**: If the dependency isn't found, return `null` instead of throwing an error.
|
|
23
|
+
- **`self`**: Only check the current `ElementInjector`. Do not look up the parent tree.
|
|
24
|
+
- **`skipSelf`**: Start searching in the parent `ElementInjector`, skipping the current element.
|
|
25
|
+
- **`host`**: Stop searching when reaching the host component's view boundary.
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
@Component({...})
|
|
29
|
+
export class Example {
|
|
30
|
+
// Returns null if not found instead of crashing
|
|
31
|
+
optionalService = inject(MyService, { optional: true });
|
|
32
|
+
|
|
33
|
+
// Skips this component's providers, looks at parent
|
|
34
|
+
parentService = inject(ParentService, { skipSelf: true });
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## `providers` vs `viewProviders`
|
|
39
|
+
|
|
40
|
+
When providing a service at the component level:
|
|
41
|
+
|
|
42
|
+
- **`providers`**: The service is available to the component, its view (template), and any **projected content** (`<ng-content>`).
|
|
43
|
+
- **`viewProviders`**: The service is available to the component and its view, but **NOT** to projected content. Use this to isolate services from content passed in by consumers.
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# Component Host Elements
|
|
2
|
+
|
|
3
|
+
The **host element** is the DOM element that matches a component's selector. The component's template renders inside this element.
|
|
4
|
+
|
|
5
|
+
## Binding to the Host Element
|
|
6
|
+
|
|
7
|
+
Use the `host` property in the `@Component` decorator to bind properties, attributes, styles, and events to the host element. This is the **preferred approach** over legacy decorators.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
@Component({
|
|
11
|
+
selector: 'custom-slider',
|
|
12
|
+
host: {
|
|
13
|
+
'role': 'slider', // Static attribute
|
|
14
|
+
'[attr.aria-valuenow]': 'value', // Attribute binding
|
|
15
|
+
'[class.active]': 'isActive()', // Class binding
|
|
16
|
+
'[style.color]': 'color()', // Style binding
|
|
17
|
+
'[tabIndex]': 'disabled ? -1 : 0', // Property binding
|
|
18
|
+
'(keydown)': 'onKeyDown($event)', // Event binding
|
|
19
|
+
},
|
|
20
|
+
})
|
|
21
|
+
export class CustomSlider {
|
|
22
|
+
value = 0;
|
|
23
|
+
disabled = false;
|
|
24
|
+
isActive = signal(false);
|
|
25
|
+
color = signal('blue');
|
|
26
|
+
|
|
27
|
+
onKeyDown(event: KeyboardEvent) {
|
|
28
|
+
/* ... */
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Legacy Decorators
|
|
34
|
+
|
|
35
|
+
`@HostBinding` and `@HostListener` are supported for backwards compatibility but should be avoided in new code.
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
export class CustomSlider {
|
|
39
|
+
@HostBinding('tabIndex')
|
|
40
|
+
get tabIndex() {
|
|
41
|
+
return this.disabled ? -1 : 0;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
@HostListener('keydown', ['$event'])
|
|
45
|
+
onKeyDown(event: KeyboardEvent) {
|
|
46
|
+
/* ... */
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Binding Collisions
|
|
52
|
+
|
|
53
|
+
If both the component (host binding) and the consumer (template binding) bind to the same property:
|
|
54
|
+
|
|
55
|
+
1. **Static vs Static**: The instance (consumer) binding wins.
|
|
56
|
+
2. **Static vs Dynamic**: The dynamic binding wins.
|
|
57
|
+
3. **Dynamic vs Dynamic**: The component's host binding wins.
|
|
58
|
+
|
|
59
|
+
## Injecting Host Attributes
|
|
60
|
+
|
|
61
|
+
Use `HostAttributeToken` with the `inject` function to read static attributes from the host element at construction time.
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import {Component, HostAttributeToken, inject} from '@angular/core';
|
|
65
|
+
|
|
66
|
+
@Component({
|
|
67
|
+
selector: 'app-btn',
|
|
68
|
+
template: `<ng-content />`,
|
|
69
|
+
})
|
|
70
|
+
export class AppButton {
|
|
71
|
+
// Throws error if 'type' is missing unless injected with { optional: true }
|
|
72
|
+
type = inject(new HostAttributeToken('type'));
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Usage:
|
|
77
|
+
|
|
78
|
+
```html
|
|
79
|
+
<app-btn type="primary">Click Me</app-btn>
|
|
80
|
+
```
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# Injection Context
|
|
2
|
+
|
|
3
|
+
The `inject()` function can only be used when code is executing within an **injection context**.
|
|
4
|
+
|
|
5
|
+
## Where is an Injection Context Available?
|
|
6
|
+
|
|
7
|
+
An injection context is automatically available in:
|
|
8
|
+
|
|
9
|
+
1. **Field initializers** of classes instantiated by DI (`@Injectable`, `@Component`, `@Directive`, `@Pipe`).
|
|
10
|
+
2. **Constructors** of classes instantiated by DI.
|
|
11
|
+
3. **Factory functions** specified in `useFactory` or `InjectionToken` configurations.
|
|
12
|
+
4. **Functional APIs** executed by Angular (e.g., functional route guards, resolvers, interceptors).
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
@Component({...})
|
|
16
|
+
export class Example {
|
|
17
|
+
// ✅ Valid: Field initializer
|
|
18
|
+
private router = inject(Router);
|
|
19
|
+
|
|
20
|
+
constructor() {
|
|
21
|
+
// ✅ Valid: Constructor
|
|
22
|
+
const http = inject(HttpClient);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
onClick() {
|
|
26
|
+
// ❌ Invalid: Not an injection context
|
|
27
|
+
// const auth = inject(AuthService);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## `runInInjectionContext`
|
|
33
|
+
|
|
34
|
+
If you need to run a function within an injection context (often needed for dynamic component creation or testing), use `runInInjectionContext`. This requires access to an existing injector (like `EnvironmentInjector` or `Injector`).
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import {Injectable, inject, EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
|
38
|
+
|
|
39
|
+
@Injectable({providedIn: 'root'})
|
|
40
|
+
export class MyService {
|
|
41
|
+
private injector = inject(EnvironmentInjector);
|
|
42
|
+
|
|
43
|
+
doSomethingDynamic() {
|
|
44
|
+
runInInjectionContext(this.injector, () => {
|
|
45
|
+
// ✅ Now valid to use inject() here
|
|
46
|
+
const router = inject(Router);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## `assertInInjectionContext`
|
|
53
|
+
|
|
54
|
+
Use `assertInInjectionContext` in utility functions to guarantee they are called from a valid context. It throws a clear error if not.
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import {assertInInjectionContext, inject, ElementRef} from '@angular/core';
|
|
58
|
+
|
|
59
|
+
export function injectNativeElement<T extends Element>(): T {
|
|
60
|
+
assertInInjectionContext(injectNativeElement);
|
|
61
|
+
return inject(ElementRef).nativeElement;
|
|
62
|
+
}
|
|
63
|
+
```
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# Inputs
|
|
2
|
+
|
|
3
|
+
Inputs allow data to flow from a parent component to a child component. Angular recommends using the signal-based `input` API for modern applications.
|
|
4
|
+
|
|
5
|
+
## Signal-based Inputs
|
|
6
|
+
|
|
7
|
+
Declare inputs using the `input()` function. This returns an `InputSignal`.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import {Component, input, computed} from '@angular/core';
|
|
11
|
+
|
|
12
|
+
@Component({
|
|
13
|
+
selector: 'app-user',
|
|
14
|
+
template: `<p>User: {{ name() }} ({{ age() }})</p>`,
|
|
15
|
+
})
|
|
16
|
+
export class User {
|
|
17
|
+
// Optional input with default value
|
|
18
|
+
name = input('Guest');
|
|
19
|
+
|
|
20
|
+
// Required input
|
|
21
|
+
age = input.required<number>();
|
|
22
|
+
|
|
23
|
+
// Inputs are reactive signals
|
|
24
|
+
label = computed(() => `Name: ${this.name()}`);
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
### Usage in Template
|
|
29
|
+
|
|
30
|
+
```html
|
|
31
|
+
<app-user [name]="userName" [age]="25" />
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Configuration Options
|
|
35
|
+
|
|
36
|
+
The `input` function accepts a config object:
|
|
37
|
+
|
|
38
|
+
- **Alias**: Change the property name used in templates.
|
|
39
|
+
- **Transform**: Modify the value before it reaches the component.
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { input, booleanAttribute } from '@angular/core';
|
|
43
|
+
|
|
44
|
+
@Component({...})
|
|
45
|
+
export class CustomButton {
|
|
46
|
+
// Alias example
|
|
47
|
+
label = input('', { alias: 'btnLabel' });
|
|
48
|
+
|
|
49
|
+
// Transform example using built-in helper
|
|
50
|
+
disabled = input(false, { transform: booleanAttribute });
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Model Inputs (Two-Way Binding)
|
|
55
|
+
|
|
56
|
+
Use `model()` to create an input that supports two-way data binding.
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
@Component({
|
|
60
|
+
selector: 'custom-counter',
|
|
61
|
+
template: `<button (click)="increment()">+</button>`,
|
|
62
|
+
})
|
|
63
|
+
export class CustomCounter {
|
|
64
|
+
value = model(0);
|
|
65
|
+
|
|
66
|
+
increment() {
|
|
67
|
+
this.value.update((v) => v + 1);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Usage
|
|
73
|
+
|
|
74
|
+
```html
|
|
75
|
+
<!-- Two-way binding with a signal -->
|
|
76
|
+
<custom-counter [(value)]="mySignal" />
|
|
77
|
+
|
|
78
|
+
<!-- Two-way binding with a plain property -->
|
|
79
|
+
<custom-counter [(value)]="myProperty" />
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Decorator-based Inputs (@Input)
|
|
83
|
+
|
|
84
|
+
The legacy API remains supported but is not recommended for new code.
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
import { Component, Input } from '@angular/core';
|
|
88
|
+
|
|
89
|
+
@Component({...})
|
|
90
|
+
export class Legacy {
|
|
91
|
+
@Input({ required: true }) value = 0;
|
|
92
|
+
@Input({ transform: trimString }) label = '';
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Best Practices
|
|
97
|
+
|
|
98
|
+
- **Prefer Signals**: Use `input()` instead of `@Input()` for better reactivity and type safety.
|
|
99
|
+
- **Required Inputs**: Use `input.required()` for mandatory data to get build-time errors.
|
|
100
|
+
- **Pure Transforms**: Ensure input transform functions are pure and statically analyzable.
|
|
101
|
+
- **Avoid Collisions**: Do not use input names that collide with standard DOM properties (e.g., `id`, `title`).
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Dependent State with `linkedSignal`
|
|
2
|
+
|
|
3
|
+
The `linkedSignal` function lets you create writable state that is intrinsically linked to some other state. It is perfect for state that needs a default value derived from an input or another signal, but can still be independently modified by the user.
|
|
4
|
+
|
|
5
|
+
If the source state changes, the `linkedSignal` resets to a new computed value.
|
|
6
|
+
|
|
7
|
+
## Basic Usage
|
|
8
|
+
|
|
9
|
+
When you only need to recompute based on a source, pass a computation function. `linkedSignal` works like `computed`, but the resulting signal is writable (you can call `.set()` or `.update()` on it).
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { Component, signal, linkedSignal } from '@angular/core';
|
|
13
|
+
|
|
14
|
+
@Component({...})
|
|
15
|
+
export class ShippingMethodPicker {
|
|
16
|
+
shippingOptions = signal(['Ground', 'Air', 'Sea']);
|
|
17
|
+
|
|
18
|
+
// Defaults to the first option.
|
|
19
|
+
// If shippingOptions changes, selectedOption resets to the new first option.
|
|
20
|
+
selectedOption = linkedSignal(() => this.shippingOptions()[0]);
|
|
21
|
+
|
|
22
|
+
changeShipping(index: number) {
|
|
23
|
+
// We can still manually update this signal!
|
|
24
|
+
this.selectedOption.set(this.shippingOptions()[index]);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Advanced Usage: Accounting for Previous State
|
|
30
|
+
|
|
31
|
+
Sometimes, when the source state changes, you want to preserve the user's manual selection if it is still valid. To do this, use the object syntax providing `source` and `computation`.
|
|
32
|
+
|
|
33
|
+
The `computation` function receives the new value of the source, and a `previous` object containing the previous source value and the previous `linkedSignal` value.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
interface ShippingMethod { id: number; name: string; }
|
|
37
|
+
|
|
38
|
+
@Component({...})
|
|
39
|
+
export class ShippingMethodPicker {
|
|
40
|
+
shippingOptions = signal<ShippingMethod[]>([
|
|
41
|
+
{id: 0, name: 'Ground'}, {id: 1, name: 'Air'}, {id: 2, name: 'Sea'}
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
selectedOption = linkedSignal<ShippingMethod[], ShippingMethod>({
|
|
45
|
+
source: this.shippingOptions,
|
|
46
|
+
computation: (newOptions, previous) => {
|
|
47
|
+
// If the newly loaded options still contain the user's previously
|
|
48
|
+
// selected option, keep it selected. Otherwise, reset to the first option.
|
|
49
|
+
return newOptions.find(opt => opt.id === previous?.value.id) ?? newOptions[0];
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### When to use `linkedSignal` vs `computed` vs `effect`
|
|
56
|
+
|
|
57
|
+
- Use `computed`: When state is **strictly** derived from other state and should never be manually updated.
|
|
58
|
+
- Use `linkedSignal`: When state is derived from other state, but the user **must** be able to override or manually update it.
|
|
59
|
+
- **Never** use `effect` to sync one piece of state to another. That is an anti-pattern. Use `computed` or `linkedSignal` instead.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# Route Loading Strategies
|
|
2
|
+
|
|
3
|
+
Angular supports two main strategies for loading routes and components to balance initial load time and navigation responsiveness.
|
|
4
|
+
|
|
5
|
+
## Eager Loading
|
|
6
|
+
|
|
7
|
+
Components are bundled into the initial JavaScript payload and are available immediately.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
{ path: 'home', component: Home }
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
- **Pros**: Seamless transitions.
|
|
14
|
+
- **Cons**: Increases initial bundle size.
|
|
15
|
+
|
|
16
|
+
## Lazy Loading
|
|
17
|
+
|
|
18
|
+
Components or routes are loaded only when the user navigates to them. This creates separate JavaScript "chunks".
|
|
19
|
+
|
|
20
|
+
### Lazy Loading Components
|
|
21
|
+
|
|
22
|
+
Use `loadComponent` to fetch the component on demand.
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
{
|
|
26
|
+
path: 'admin',
|
|
27
|
+
loadComponent: () => import('./admin/admin.component').then(m => m.AdminComponent)`,
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### Lazy Loading Child Routes
|
|
32
|
+
|
|
33
|
+
Use `loadChildren` to fetch a set of routes.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
{
|
|
37
|
+
path: 'settings',
|
|
38
|
+
loadChildren: () => import('./settings/settings.routes'),
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Injection Context and Lazy Loading
|
|
43
|
+
|
|
44
|
+
Loader functions run within the **injection context** of the current route. This allows you to call `inject()` to make context-aware loading decisions.
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
{
|
|
48
|
+
path: 'dashboard',
|
|
49
|
+
loadComponent: () => {
|
|
50
|
+
const flags = inject(FeatureFlags);
|
|
51
|
+
return flags.isPremium
|
|
52
|
+
? import('./premium-dashboard')
|
|
53
|
+
: import('./basic-dashboard');
|
|
54
|
+
},
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Recommendation
|
|
59
|
+
|
|
60
|
+
- Use **Eager Loading** for the primary landing pages.
|
|
61
|
+
- Use **Lazy Loading** for all other feature areas to keep the initial bundle small.
|