diff --git a/.github/workflows/dev-infra.yml b/.github/workflows/dev-infra.yml index 48e6cba7bef2..71aca25eb2d3 100644 --- a/.github/workflows/dev-infra.yml +++ b/.github/workflows/dev-infra.yml @@ -16,6 +16,7 @@ jobs: - uses: angular/dev-infra/github-actions/pull-request-labeling@e006a332028a4c3cb24e9d92437fac7ae99e2ed5 with: angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }} + labels: '{"requires: TGP": ["packages/core/primitives/**/{*,.*}"]}' post_approval_changes: runs-on: ubuntu-latest steps: diff --git a/.pullapprove.yml b/.pullapprove.yml index 9cd37692e09a..45a7e962ba78 100644 --- a/.pullapprove.yml +++ b/.pullapprove.yml @@ -481,10 +481,6 @@ groups: - thePunderWoman # Jessica Janiuk - AndrewKushnir # Andrew Kushnir - atscott # Andrew Scott - labels: - pending: 'requires: TGP' - approved: 'requires: TGP' - rejected: 'requires: TGP' # External team required reviews primitives-shared: @@ -502,10 +498,6 @@ groups: - tbondwilkinson # Tom Wilkinson - rahatarmanahmed # Rahat Ahmed - ENAML # Ethan Cline - labels: - pending: 'requires: TGP' - approved: 'requires: TGP' - rejected: 'requires: TGP' #################################################################################### # Override managed result groups diff --git a/adev/src/app/routing/navigation-entries/index.ts b/adev/src/app/routing/navigation-entries/index.ts index 0117ceb6eaae..35be26c71ac5 100644 --- a/adev/src/app/routing/navigation-entries/index.ts +++ b/adev/src/app/routing/navigation-entries/index.ts @@ -341,6 +341,12 @@ export const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [ path: 'guide/di/di-in-action', contentPath: 'guide/di/di-in-action', }, + { + label: 'Debugging and troubleshooting DI', + path: 'guide/di/debugging-and-troubleshooting-di', + contentPath: 'guide/di/debugging-and-troubleshooting-di', + status: 'new', + }, ], }, { diff --git a/adev/src/content/guide/di/debugging-and-troubleshooting-di.md b/adev/src/content/guide/di/debugging-and-troubleshooting-di.md new file mode 100644 index 000000000000..e5f9ae964414 --- /dev/null +++ b/adev/src/content/guide/di/debugging-and-troubleshooting-di.md @@ -0,0 +1,1018 @@ +# Debugging and troubleshooting dependency injection + +Dependency injection (DI) issues typically stem from configuration mistakes, scope problems, or incorrect usage patterns. This guide helps you identify and resolve common DI problems that developers encounter. + +## Common pitfalls and solutions + +### Services not available where expected + +One of the most common DI issues occurs when you try to inject a service but Angular cannot find it in the current injector or any parent injector. This usually happens when the service is provided in the wrong scope or not provided at all. + +#### Provider scope mismatch + +When you provide a service in a component's `providers` array, Angular creates an instance in that component's injector. This instance is only available to that component and its children. Parent components and sibling components cannot access it because they use different injectors. + +```angular-ts {header: 'child-view.ts'} +import {Component} from '@angular/core'; +import {DataStore} from './data-store'; + +@Component({ + selector: 'app-child', + template: '

Child

', + providers: [DataStore], // Only available in this component and its children +}) +export class ChildView {} +``` + +```angular-ts {header: 'parent-view.ts'} +import {Component, inject} from '@angular/core'; +import {DataStore} from './data-store'; + +@Component({ + selector: 'app-parent', + template: '', +}) +export class ParentView { + private dataService = inject(DataStore); // ERROR: Not available to parent +} +``` + +Angular only searches up the hierarchy, never down. Parent components cannot access services provided in child components. + +**Solution:** Provide the service at a higher level (application or parent component). + +```ts {prefer} +import {Injectable} from '@angular/core'; + +@Injectable({providedIn: 'root'}) +export class DataStore { + // Available everywhere +} +``` + +TIP: Use `providedIn: 'root'` by default for services that don't need component-specific state. This makes services available everywhere and enables tree-shaking. + +#### Services and lazy-loaded routes + +When you provide a service in a lazy-loaded route's `providers` array, Angular creates a child injector for that route. This injector and its services only become available after the route loads. Components in the eagerly-loaded parts of your application cannot access these services because they use different injectors that exist before the lazy-loaded injector is created. + +```ts {header: 'feature.routes.ts'} +import {Routes} from '@angular/router'; +import {FeatureClient} from './feature-client'; + +export const featureRoutes: Routes = [ + { + path: 'feature', + providers: [FeatureClient], + loadComponent: () => import('./feature-view'), + }, +]; +``` + +```angular-ts {header: 'eager-view.ts'} +import {Component, inject} from '@angular/core'; +import {FeatureClient} from './feature-client'; + +@Component({ + selector: 'app-eager', + template: '

Eager Component

', +}) +export class EagerView { + private featureService = inject(FeatureClient); // ERROR: Not available yet +} +``` + +Lazy-loaded routes create child injectors that are only available after the route loads. + +NOTE: By default, route injectors and their services persist even after navigating away from the route. They are not destroyed until the application is closed. For automatic cleanup of unused route injectors, see [customizing route behavior](guide/routing/customizing-route-behavior#experimental-automatic-cleanup-of-unused-route-injectors). + +**Solution:** Use `providedIn: 'root'` for services that need to be shared across lazy boundaries. + +```ts {prefer, header: 'Provide at root for shared services'} +import {Injectable} from '@angular/core'; + +@Injectable({providedIn: 'root'}) +export class FeatureClient { + // Available everywhere, including before lazy load +} +``` + +If the service should be lazy-loaded but still available to eager components, inject it only where needed and use optional injection to handle availability. + +### Multiple instances instead of singletons + +You expect one shared instance (singleton) but get separate instances in different components. + +#### Providing in component instead of root + +When you add a service to a component's `providers` array, Angular creates a new instance of that service for each instance of the component. Each component gets its own separate service instance, which means changes in one component don't affect the service instance in other components. This is often unexpected when you want shared state across your application. + +```angular-ts {avoid, header: 'Component-level provider creates multiple instances'} +import {Component, inject} from '@angular/core'; +import {UserClient} from './user-client'; + +@Component({ + selector: 'app-profile', + template: '

Profile

', + providers: [UserClient], // Creates new instance per component! +}) +export class UserProfile { + private userService = inject(UserClient); +} + +@Component({ + selector: 'app-settings', + template: '

Settings

', + providers: [UserClient], // Different instance! +}) +export class UserSettings { + private userService = inject(UserClient); +} +``` + +Each component gets its own `UserClient` instance. Changes in one component don't affect the other. + +**Solution:** Use `providedIn: 'root'` for singletons. + +```ts {prefer, header: 'Root-level singleton'} +import {Injectable} from '@angular/core'; + +@Injectable({providedIn: 'root'}) +export class UserClient { + // Single instance shared across all components +} +``` + +#### When multiple instances are intentional + +Sometimes you want separate instances per component for component-specific state. + +```angular-ts {header: 'Intentional: Component-scoped state'} +import {Injectable, signal} from '@angular/core'; + +@Injectable() // No providedIn - must be provided explicitly +export class FormStateStore { + private formData = signal({}); + + setData(data: any) { + this.formData.set(data); + } + + getData() { + return this.formData(); + } +} + +@Component({ + selector: 'app-user-form', + template: '
...
', + providers: [FormStateStore], // Each form gets its own state +}) +export class UserForm { + private formState = inject(FormStateStore); +} +``` + +This pattern is useful for: + +- Form state management (each form has isolated state) +- Component-specific caching +- Temporary data that shouldn't be shared + +### Incorrect inject() usage + +The `inject()` function only works in specific contexts during class construction and factory execution. + +#### Using inject() in lifecycle hooks + +When you call the `inject()` function inside lifecycle hooks like `ngOnInit()`, `ngAfterViewInit()`, or `ngOnDestroy()`, Angular throws an error because these methods run outside the injection context. The injection context is only available during the synchronous execution of class construction, which happens before lifecycle hooks are called. + +```angular-ts {avoid, header: 'inject() in ngOnInit'} +import {Component, inject} from '@angular/core'; +import {UserClient} from './user-client'; + +@Component({ + selector: 'app-profile', + template: '

User: {{userName}}

', +}) +export class UserProfile { + userName = ''; + + ngOnInit() { + const userService = inject(UserClient); // ERROR: Not an injection context + this.userName = userService.getUser().name; + } +} +``` + +**Solution:** Capture dependencies and derive values in field initializers. + +```angular-ts {prefer, header: 'Derive values in field initializers'} +import {Component, inject} from '@angular/core'; +import {UserClient} from './user-client'; + +@Component({ + selector: 'app-profile', + template: '

User: {{userName}}

', +}) +export class UserProfile { + private userService = inject(UserClient); + userName = this.userService.getUser().name; +} +``` + +#### Using the Injector for deferred injection + +When you need to retrieve services outside an injection context, use the captured `Injector` directly with `injector.get()`: + +```angular-ts +import {Component, inject, Injector} from '@angular/core'; +import {UserClient} from './user-client'; + +@Component({ + selector: 'app-profile', + template: '', +}) +export class UserProfile { + private injector = inject(Injector); + + delayedLoad() { + setTimeout(() => { + const userService = this.injector.get(UserClient); + console.log(userService.getUser()); + }, 1000); + } +} +``` + +#### Using runInInjectionContext for callbacks + +Use `runInInjectionContext()` when you need to enable **other code** to call `inject()`. This is useful when accepting callbacks that might use dependency injection: + +```angular-ts +import {Component, inject, Injector, input} from '@angular/core'; + +@Component({ + selector: 'app-data-loader', + template: '', +}) +export class DataLoader { + private injector = inject(Injector); + onLoad = input<() => void>(); + + load() { + const callback = this.onLoad(); + if (callback) { + // Enable the callback to use inject() + this.injector.runInInjectionContext(callback); + } + } +} +``` + +The `runInInjectionContext()` method creates a temporary injection context, allowing code inside the callback to call `inject()`. + +IMPORTANT: Always capture dependencies at the class level when possible. Use `injector.get()` for simple deferred retrieval, and `runInInjectionContext()` only when external code needs to call `inject()`. + +TIP: Use `assertInInjectionContext()` to verify your code is running in a valid injection context. This is useful when creating reusable functions that call `inject()`. See [Asserting the context](guide/di/dependency-injection-context#asserts-the-context) for details. + +### providers vs viewProviders confusion + +The difference between `providers` and `viewProviders` affects content projection scenarios. + +#### Understanding the difference + +**providers:** Available to the component's template AND any content projected into the component (ng-content). + +**viewProviders:** Only available to the component's template, NOT to projected content. + +```angular-ts {header: 'parent-view.ts'} +import {Component, inject} from '@angular/core'; +import {ThemeStore} from './theme-store'; + +@Component({ + selector: 'app-parent', + template: ` +
+

Theme: {{ themeService.theme() }}

+ +
+ `, + providers: [ThemeStore], // Available to content children +}) +export class ParentView { + protected themeService = inject(ThemeStore); +} + +@Component({ + selector: 'app-parent-view', + template: ` +
+

Theme: {{ themeService.theme() }}

+ +
+ `, + viewProviders: [ThemeStore], // NOT available to content children +}) +export class ParentViewOnly { + protected themeService = inject(ThemeStore); +} +``` + +```angular-ts {header: 'child-view.ts'} +import {Component, inject} from '@angular/core'; +import {ThemeStore} from './theme-store'; + +@Component({ + selector: 'app-child', + template: '

Child theme: {{theme()}}

', +}) +export class ChildView { + private themeService = inject(ThemeStore, {optional: true}); + theme = () => this.themeService?.theme() ?? 'none'; +} +``` + +```angular-ts {header: 'app.ts'} +@Component({ + selector: 'app-root', + template: ` + + + + + + + + + + `, +}) +export class App {} +``` + +**When projected into `app-parent`:** The child component can inject `ThemeStore` because `providers` makes it available to projected content. + +**When projected into `app-parent-view`:** The child component cannot inject `ThemeStore` because `viewProviders` restricts it to the parent's template only. + +#### Choosing between providers and viewProviders + +Use `providers` when: + +- The service should be available to projected content +- You want content children to access the service +- You're providing general-purpose services + +Use `viewProviders` when: + +- The service should only be available to your component's template +- You want to hide implementation details from projected content +- You're providing internal services that shouldn't leak out + +**Default recommendation:** Use `providers` unless you have a specific reason to restrict access with `viewProviders`. + +### InjectionToken issues + +When using `InjectionToken` for non-class dependencies, developers often encounter problems related to token identity, type safety, and provider configuration. These issues usually stem from how JavaScript handles object identity and how TypeScript infers types. + +#### Token identity confusion + +When you create a new `InjectionToken` instance, JavaScript creates a unique object in memory. Even if you create another `InjectionToken` with the exact same description string, it's a completely different object. Angular uses the token object's identity (not its description) to match providers with injection points, so tokens with the same description but different object identities cannot access each other's values. + +```ts {header: 'config.token.ts'} +import {InjectionToken} from '@angular/core'; + +export interface AppConfig { + apiUrl: string; +} + +export const APP_CONFIG = new InjectionToken('app config'); +``` + +```ts {header: 'app.config.ts'} +import {APP_CONFIG} from './config.token'; + +export const appConfig: AppConfig = { + apiUrl: 'https://api.example.com', +}; + +bootstrapApplication(App, { + providers: [{provide: APP_CONFIG, useValue: appConfig}], +}); +``` + +```angular-ts {avoid, header: 'feature-view.ts'} +// Creating new token with same description +import {InjectionToken, inject} from '@angular/core'; +import {AppConfig} from './config.token'; + +const APP_CONFIG = new InjectionToken('app config'); + +@Component({ + selector: 'app-feature', + template: '

Feature

', +}) +export class FeatureView { + private config = inject(APP_CONFIG); // ERROR: Different token instance! +} +``` + +Even though both tokens have the description `'app config'`, they are different objects. Angular compares tokens by reference, not by description. + +**Solution:** Import the same token instance. + +```angular-ts {prefer, header: 'feature-view.ts'} +import {inject} from '@angular/core'; +import {APP_CONFIG, AppConfig} from './config.token'; + +@Component({ + selector: 'app-feature', + template: '

API: {{config.apiUrl}}

', +}) +export class FeatureView { + protected config = inject(APP_CONFIG); // Works: Same token instance +} +``` + +TIP: Always export tokens from a shared file and import them everywhere they're needed. Never create multiple `InjectionToken` instances with the same description. + +#### Trying to inject interfaces + +When you define a TypeScript interface, it only exists during compilation for type checking. TypeScript erases all interface definitions when it compiles to JavaScript, so at runtime there's no object for Angular to use as an injection token. If you try to inject an interface type, Angular has nothing to match against the provider configuration. + +```angular-ts {avoid, header: 'Can't inject interface'} +interface UserConfig { + name: string; + email: string; +} + +@Component({ + selector: 'app-profile', + template: '

Profile

', +}) +export class UserProfile { + // ERROR: Interfaces don't exist at runtime + constructor(private config: UserConfig) {} +} +``` + +**Solution:** Use `InjectionToken` for interface types. + +```angular-ts {prefer, header: 'Use InjectionToken for interfaces'} +import {InjectionToken, inject} from '@angular/core'; + +interface UserConfig { + name: string; + email: string; +} + +export const USER_CONFIG = new InjectionToken('user configuration'); + +// Provide the configuration +bootstrapApplication(App, { + providers: [ + { + provide: USER_CONFIG, + useValue: {name: 'Alice', email: 'alice@example.com'}, + }, + ], +}); + +// Inject using the token +@Component({ + selector: 'app-profile', + template: '

User: {{config.name}}

', +}) +export class UserProfile { + protected config = inject(USER_CONFIG); +} +``` + +The `InjectionToken` exists at runtime and can be used for injection, while the `UserConfig` interface provides type safety during development. + +### Circular dependencies + +Circular dependencies occur when services inject each other, creating a cycle that Angular cannot resolve. For detailed explanations and code examples, see [NG0200: Circular dependency](errors/NG0200). + +**Resolution strategies** (in order of preference): + +1. **Restructure** - Extract shared logic to a third service, breaking the cycle +2. **Use events** - Replace direct dependencies with event-based communication (such as `Subject`) +3. **Lazy injection** - Use `Injector.get()` to defer one dependency (last resort) + +NOTE: Do not use `forwardRef()` for service circular dependencies—it only solves circular imports in standalone component configurations. + +## Debugging dependency resolution + +### Understanding the resolution process + +Angular resolves dependencies by walking up the injector hierarchy. When a `NullInjectorError` occurs, understanding this search order helps you identify where to add the missing provider. + +Angular searches in this order: + +1. **Element injector** - The current component or directive +2. **Parent element injectors** - Up the DOM tree through parent components +3. **Environment injector** - The route or application injector +4. **NullInjector** - Throws `NullInjectorError` if not found + +When you see a `NullInjectorError`, the service isn't provided at any level the component can access. Check that: + +- The service has `@Injectable({providedIn: 'root'})`, or +- The service is in a `providers` array the component can reach + +You can modify this search behavior with resolution modifiers like `self`, `skipSelf`, `host`, and `optional`. For complete coverage of resolution rules and modifiers, see the [Hierarchical injectors guide](guide/di/hierarchical-dependency-injection). + +### Using Angular DevTools + +Angular DevTools includes an injector tree inspector that visualizes the entire injector hierarchy and shows which providers are available at each level. For installation and general usage, see the [Angular DevTools injector documentation](tools/devtools/injectors). + +When debugging DI issues, use DevTools to answer these questions: + +- **Is the service provided?** Select the component that fails to inject and check if the service appears in the Injector section. +- **At what level?** Walk up the component tree to find where the service is actually provided (component, route, or application level). +- **Multiple instances?** If a singleton service appears in multiple component injectors, it's likely provided in component `providers` arrays instead of using `providedIn: 'root'`. + +If a service never appears in any injector, verify it has the `@Injectable()` decorator with `providedIn: 'root'` or is listed in a `providers` array. + +### Logging and tracing injection + +When DevTools isn't enough, use logging to trace injection behavior. + +#### Logging service creation + +Add console logs to service constructors to see when services are created. + +```ts +import {Injectable} from '@angular/core'; + +@Injectable({providedIn: 'root'}) +export class UserClient { + constructor() { + console.log('UserClient created'); + console.trace(); // Shows call stack + } + + getUser() { + return {name: 'Alice'}; + } +} +``` + +When the service is created, you'll see the log message and a stack trace showing where the injection occurred. + +**What to look for:** + +- How many times is the constructor called? (should be once for singletons) +- Where in the code is it being injected? (check the stack trace) +- Is it created at the expected time? (application startup vs lazy) + +#### Checking service availability + +Use optional injection with logging to determine if a service is available. + +```angular-ts +import {Component, inject} from '@angular/core'; +import {UserClient} from './user-client'; + +@Component({ + selector: 'app-debug', + template: '

Debug Component

', +}) +export class DebugView { + private userService = inject(UserClient, {optional: true}); + + constructor() { + if (this.userService) { + console.log('UserClient available:', this.userService); + } else { + console.warn('UserClient NOT available'); + console.trace(); // Shows where we tried to inject + } + } +} +``` + +This pattern helps you verify if a service is available without crashing the application. + +#### Logging resolution modifiers + +Test different resolution strategies with logging. + +```angular-ts +import {Component, inject} from '@angular/core'; +import {UserClient} from './user-client'; + +@Component({ + selector: 'app-debug', + template: '

Debug Component

', + providers: [UserClient], +}) +export class DebugView { + // Try to get local instance + private localService = inject(UserClient, {self: true, optional: true}); + + // Try to get parent instance + private parentService = inject(UserClient, { + skipSelf: true, + optional: true, + }); + + constructor() { + console.log('Local instance:', this.localService); + console.log('Parent instance:', this.parentService); + console.log('Same instance?', this.localService === this.parentService); + } +} +``` + +This shows you which instances are available at different injector levels. + +### Debugging workflow + +When DI fails, follow this systematic approach: + +**Step 1: Read the error message** + +- Identify the error code (NG0200, NG0203, etc.) +- Read the dependency path +- Note which token failed + +**Step 2: Check the basics** + +- Does the service have `@Injectable()`? +- Is `providedIn` set correctly? +- Are imports correct? +- Is the file included in compilation? + +**Step 3: Verify injection context** + +- Is `inject()` called in a valid context? +- Check for async issues (await, setTimeout, promises) +- Verify timing (not after destroy) + +**Step 4: Use debugging tools** + +- Open Angular DevTools +- Check injector hierarchy +- Add console logs to constructors +- Use optional injection to test availability + +**Step 5: Simplify and isolate** + +- Remove dependencies one by one +- Test in a minimal component +- Check each injector level separately +- Create a reproduction case + +## DI error reference + +This section provides detailed information about specific Angular DI error codes you may encounter. Use this as a reference when you see these errors in your console. + +### NullInjectorError: No provider for [Service] + +**Error code:** None (displayed as `NullInjectorError`) + +This error occurs when Angular cannot find a provider for a token in the injector hierarchy. The error message includes a dependency path showing where the injection was attempted. + +``` +NullInjectorError: No provider for UserClient! + Dependency path: App -> AuthClient -> UserClient +``` + +The dependency path shows that `App` injected `AuthClient`, which tried to inject `UserClient`, but no provider was found. + +#### Missing @Injectable decorator + +The most common cause is forgetting the `@Injectable()` decorator on a service class. + +```ts {avoid, header: 'Missing decorator'} +export class UserClient { + getUser() { + return {name: 'Alice'}; + } +} +``` + +Angular requires the `@Injectable()` decorator to generate the metadata needed for dependency injection. + +```ts {prefer, header: 'Include @Injectable'} +import {Injectable} from '@angular/core'; + +@Injectable({ + providedIn: 'root', +}) +export class UserClient { + getUser() { + return {name: 'Alice'}; + } +} +``` + +NOTE: Classes with zero-argument constructors can work without `@Injectable()`, but this is not recommended. Always include the decorator for consistency and to avoid issues when adding dependencies later. + +#### Missing providedIn configuration + +A service may have `@Injectable()` but not specify where it should be provided. + +```ts {avoid, header: 'No providedIn specified'} +import {Injectable} from '@angular/core'; + +@Injectable() +export class UserClient { + getUser() { + return {name: 'Alice'}; + } +} +``` + +Specify `providedIn: 'root'` to make the service available throughout your application. + +```ts {prefer, header: 'Specify providedIn'} +import {Injectable} from '@angular/core'; + +@Injectable({ + providedIn: 'root', +}) +export class UserClient { + getUser() { + return {name: 'Alice'}; + } +} +``` + +The `providedIn: 'root'` configuration makes the service available application-wide and enables tree-shaking (the service is removed from the bundle if never injected). + +#### Standalone component missing imports + +In Angular v20+ with standalone components, you must explicitly import or provide dependencies in each component. + +```angular-ts {avoid, header: 'Missing service import'} +import {Component, inject} from '@angular/core'; +import {UserClient} from './user-client'; + +@Component({ + selector: 'app-profile', + template: '

User: {{user().name}}

', +}) +export class UserProfile { + private userService = inject(UserClient); // ERROR: No provider + user = this.userService.getUser(); +} +``` + +Ensure the service uses `providedIn: 'root'` or add it to the component's `providers` array. + +```angular-ts {prefer, header: 'Service uses providedIn: root'} +import {Component, inject} from '@angular/core'; +import {UserClient} from './user-client'; + +@Component({ + selector: 'app-profile', + template: '

User: {{user().name}}

', +}) +export class UserProfile { + private userService = inject(UserClient); // Works: providedIn: 'root' + user = this.userService.getUser(); +} +``` + +#### Debugging with the dependency path + +The dependency path in the error message shows the chain of injections that led to the failure. + +``` +NullInjectorError: No provider for LoggerStore! + Dependency path: App -> DataStore -> ApiClient -> LoggerStore +``` + +This path tells you: + +1. `App` injected `DataStore` +2. `DataStore` injected `ApiClient` +3. `ApiClient` tried to inject `LoggerStore` +4. No provider for `LoggerStore` was found + +Start your investigation at the end of the chain (`LoggerStore`) and verify it has proper configuration. + +#### Checking provider availability with optional injection + +Use optional injection to check if a provider exists without throwing an error. + +```angular-ts +import {Component, inject} from '@angular/core'; +import {UserClient} from './user-client'; + +@Component({ + selector: 'app-debug', + template: '

Service available: {{serviceAvailable}}

', +}) +export class DebugView { + private userService = inject(UserClient, {optional: true}); + serviceAvailable = this.userService !== null; +} +``` + +Optional injection returns `null` if no provider is found, allowing you to handle the absence gracefully. + +### NG0203: inject() must be called from an injection context + +**Error code:** NG0203 + +This error occurs when you call `inject()` outside of a valid injection context. Angular requires `inject()` to be called synchronously during class construction or factory execution. + +``` +NG0203: inject() must be called from an injection context such as a +constructor, a factory function, a field initializer, or a function +used with `runInInjectionContext`. +``` + +#### Valid injection contexts + +Angular allows `inject()` in these locations: + +1. **Class field initializers** + + ```angular-ts + import {Component, inject} from '@angular/core'; + import {UserClient} from './user-client'; + + @Component({ + selector: 'app-profile', + template: '

User: {{user().name}}

', + }) + export class UserProfile { + private userService = inject(UserClient); // Valid + user = this.userService.getUser(); + } + ``` + +2. **Class constructor** + + ```angular-ts + import {Component, inject} from '@angular/core'; + import {UserClient} from './user-client'; + + @Component({ + selector: 'app-profile', + template: '

User: {{user().name}}

', + }) + export class UserProfile { + private userService: UserClient; + + constructor() { + this.userService = inject(UserClient); // Valid + } + + user = this.userService.getUser(); + } + ``` + +3. **Provider factory functions** + + ```ts + import {inject, InjectionToken} from '@angular/core'; + import {UserClient} from './user-client'; + + export const GREETING = new InjectionToken('greeting', { + factory() { + const userService = inject(UserClient); // Valid + const user = userService.getUser(); + return `Hello, ${user.name}`; + }, + }); + ``` + +4. **Inside runInInjectionContext()** + + ```angular-ts + import {Component, inject, Injector} from '@angular/core'; + import {UserClient} from './user-client'; + + @Component({ + selector: 'app-profile', + template: '', + }) + export class UserProfile { + private injector = inject(Injector); + + loadUser() { + this.injector.runInInjectionContext(() => { + const userService = inject(UserClient); // Valid + console.log(userService.getUser()); + }); + } + } + ``` + +Other injection contexts that `inject()` also works in include: + +- [provideAppInitializer](api/core/provideAppInitializer) +- [provideEnvironmentInitializer](api/core/provideEnvironmentInitializer) +- Functional [route guards](guide/routing/route-guards) +- Functional [data resolvers](guide/routing/data-resolvers) + +#### When this error occurs + +This error occurs when: + +- Calling `inject()` in lifecycle hooks (`ngOnInit`, `ngAfterViewInit`, etc.) +- Calling `inject()` after `await` in async functions +- Calling `inject()` in callbacks (`setTimeout`, `Promise.then()`, etc.) +- Calling `inject()` outside of class construction phase + +See the "Incorrect inject() usage" section for detailed examples and solutions. + +#### Solutions and workarounds + +**Solution 1:** Capture dependencies in field initializers (most common) + +```ts +private userService = inject(UserClient) // Capture at class level +``` + +**Solution 2:** Use `runInInjectionContext()` for callbacks + +```ts +private injector = inject(Injector) + +someCallback() { + this.injector.runInInjectionContext(() => { + const service = inject(MyClient) + }) +} +``` + +**Solution 3:** Pass dependencies as parameters instead of injecting them + +```ts +// Instead of injecting inside a callback +setTimeout(() => { + const service = inject(MyClient) // ERROR +}, 1000) + +// Capture first, then use +private service = inject(MyClient) + +setTimeout(() => { + this.service.doSomething() // Use captured reference +}, 1000) +``` + +### NG0200: Circular dependency detected + +**Error code:** NG0200 + +This error occurs when two or more services depend on each other, creating a circular dependency that Angular cannot resolve. + +``` +NG0200: Circular dependency in DI detected for AuthClient + Dependency path: AuthClient -> UserClient -> AuthClient +``` + +The dependency path shows the cycle: `AuthClient` depends on `UserClient`, which depends back on `AuthClient`. + +#### Understanding the error + +Angular creates service instances by calling their constructors and injecting dependencies. When services depend on each other circularly, Angular cannot determine which to create first. + +#### Common causes + +- Direct circular dependency (Service A → Service B → Service A) +- Indirect circular dependency (Service A → Service B → Service C → Service A) +- Import cycles in module files that also have service dependencies + +#### Resolution strategies + +See the "Circular dependencies" section for detailed examples and solutions: + +1. **Restructure** - Extract shared logic to a third service (recommended) +2. **Use events** - Replace direct dependencies with event-based communication +3. **Lazy injection** - Use `Injector.get()` to defer one dependency (last resort) + +Do NOT use `forwardRef()` for service circular dependencies. It only solves circular imports in component configurations. + +### Other DI error codes + +For detailed explanations and solutions for these errors, see the [Angular error reference](errors): + +| Error Code | Description | +| ----------------------- | ------------------------------------------------------------------------------------------ | +| [NG0204](errors/NG0204) | Can't resolve all parameters - missing `@Injectable()` decorator | +| [NG0205](errors/NG0205) | Injector already destroyed - accessing services after component destruction | +| [NG0207](errors/NG0207) | EnvironmentProviders in wrong context - using `provideHttpClient()` in component providers | + +## Next steps + +When you encounter DI errors, remember to: + +1. Read the error message and dependency path carefully +2. Verify basic configuration (decorators, `providedIn`, imports) +3. Check injection context and timing +4. Use DevTools and logging to investigate +5. Simplify and isolate the problem + +For a deeper understanding of specific topics on dependency injection, check out: + +- [Understanding dependency injection](guide/di) - Core DI concepts and patterns +- [Hierarchical dependency injection](guide/di/hierarchical-dependency-injection) - How the injector hierarchy works +- [Testing with dependency injection](guide/testing) - Using TestBed and mocking dependencies diff --git a/adev/src/content/reference/errors/NG0204.md b/adev/src/content/reference/errors/NG0204.md new file mode 100644 index 000000000000..55077d2dda83 --- /dev/null +++ b/adev/src/content/reference/errors/NG0204.md @@ -0,0 +1,59 @@ +# Invalid Injection Token + +This error occurs when Angular cannot resolve a dependency for a class during dependency injection. This most commonly affects classes using constructor injection, where Angular relies on TypeScript metadata to determine parameter types. + +The most common causes are: + +1. A service class is missing the `@Injectable()` decorator +2. An `InjectionToken` lacks a proper provider definition +3. A constructor parameter cannot be resolved + +NOTE: The `inject()` function takes an explicit token, so the "unresolvable parameter" scenario does not apply to it directly. However, if the injected class itself is missing `@Injectable()` and has its own constructor dependencies, the error can still occur. + +## Common scenarios + +### Missing `@Injectable()` decorator + +When a class has constructor dependencies but lacks the `@Injectable()` decorator, Angular cannot resolve its parameters: + +```ts {header: 'Missing @Injectable() decorator'} +export class UserClient { + constructor(private http: HttpClient) {} // Angular can't resolve this +} +``` + +Add the `@Injectable()` decorator to fix this: + +```ts +@Injectable({providedIn: 'root'}) +export class UserClient { + constructor(private http: HttpClient) {} +} +``` + +### Unresolvable constructor parameters + +This error also appears when Angular cannot determine the type of a constructor parameter: + +```ts +@Injectable({providedIn: 'root'}) +export class DataStore { + // Angular can't resolve 'config' without a provider + constructor(private config: AppConfig) {} +} +``` + +Ensure all constructor parameters either have providers configured or use `@Optional()` for optional dependencies. + +## Debugging the error + +The error message includes details about which token could not be resolved: + +- `Can't resolve all parameters for X: (?, ?, ?)` — The `?` marks indicate unresolvable parameters. Check that the class has `@Injectable()` and all dependencies have providers. +- `Token X is missing a ɵprov definition` — An `InjectionToken` was used without configuring a provider. Register the token with a value using `{provide: TOKEN, useValue: ...}` or add a default factory to the token definition. + +Work backwards from the error's stack trace to identify where the problematic injection occurs, then verify that: + +1. The class has `@Injectable()` decorator +2. All constructor parameters have registered providers +3. Any `InjectionToken` has a configured provider or default value diff --git a/adev/src/content/reference/errors/NG0205.md b/adev/src/content/reference/errors/NG0205.md new file mode 100644 index 000000000000..f3b3b2315591 --- /dev/null +++ b/adev/src/content/reference/errors/NG0205.md @@ -0,0 +1,76 @@ +# Injector has already been destroyed + +This error occurs when you attempt to retrieve a service from an injector that has already been destroyed. This typically happens when code tries to access dependencies after a component, directive, or module has been destroyed. + +## Common scenarios + +### Accessing services in callbacks after destruction + +When a component is destroyed, its injector is also destroyed. If an async callback later tries to access services, this error occurs: + +```ts +@Component({ + /*...*/ +}) +export class UserProfile implements OnInit { + private userClient = inject(UserClient); + + ngOnInit() { + setTimeout(() => { + // ERROR: If component was destroyed before timeout fires, + // the injector is no longer available + this.userClient.fetchData(); + }, 5000); + } +} +``` + +### Accessing services after unsubscribing + +Similar issues occur with observables if cleanup happens in the wrong order: + +```ts +@Component({ + /*...*/ +}) +export class DataView implements OnDestroy { + private dataStore = inject(DataStore); + + ngOnDestroy() { + // Problematic: attempting to use the injector during destruction + // after other cleanup may have occurred + this.dataStore.cleanup(); + } +} +``` + +## Debugging the error + +To fix this error: + +1. **Check async operations** — Ensure callbacks, promises, and subscriptions are cancelled when the component is destroyed. Use `takeUntilDestroyed()` or `DestroyRef` for cleanup. + +2. **Capture dependencies early** — Store references to services in class fields rather than accessing the injector in callbacks. + +3. **Guard against destroyed state** — For operations that might outlive the component, check if the component is still active before accessing services. + +```ts +@Component({ + /*...*/ +}) +export class UserProfile implements OnInit { + private destroyRef = inject(DestroyRef); + private userClient = inject(UserClient); + + ngOnInit() { + // Use takeUntilDestroyed to automatically cancel when destroyed + interval(5000) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { + this.userClient.fetchData(); + }); + } +} +``` + +The stack trace indicates where the destroyed injector was accessed. Work backwards to identify the async operation that outlived its component. diff --git a/adev/src/content/reference/errors/NG0207.md b/adev/src/content/reference/errors/NG0207.md new file mode 100644 index 000000000000..b02643e26a5a --- /dev/null +++ b/adev/src/content/reference/errors/NG0207.md @@ -0,0 +1,75 @@ +# EnvironmentProviders in wrong context + +This error occurs when `EnvironmentProviders` are used in a context that only accepts regular providers, such as a component's `providers` array. Environment providers are designed for application-wide configuration and can only be used in environment injectors (like the root injector configured in `bootstrapApplication` or route configurations). + +## Common scenarios + +### Using `provideHttpClient()` in component providers + +Functions like `provideHttpClient()` return `EnvironmentProviders`, which cannot be used at the component level: + +```ts +@Component({ + providers: [ + provideHttpClient(), // ERROR: EnvironmentProviders can't be used here + ], +}) +export class UserProfile {} +``` + +### Using `importProvidersFrom()` in component providers + +The `importProvidersFrom()` function also returns `EnvironmentProviders`: + +```ts +@Component({ + providers: [ + importProvidersFrom(SomeModule), // ERROR: can't be used for component providers + ], +}) +export class DataView {} +``` + +## Debugging the error + +Move the environment providers to an appropriate location: + +### For application-wide providers + +Configure environment providers in `bootstrapApplication`: + +```ts +bootstrapApplication(App, { + providers: [provideHttpClient(), importProvidersFrom(SomeModule)], +}); +``` + +### For route-specific providers + +Use the `providers` array in route configurations: + +```ts +const routes: Routes = [ + { + path: 'admin', + component: AdminView, + providers: [provideHttpClient(withInterceptors([authInterceptor]))], + }, +]; +``` + +### For component-level services + +If you need component-scoped services, use regular providers instead of environment providers: + +```ts +@Component({ + providers: [ + UserClient, // Regular provider - this works + {provide: API_URL, useValue: '/api'}, // Value provider - this works + ], +}) +export class UserProfile {} +``` + +The error message specifies which provider caused the issue. Check that all items in your component's `providers` array are regular providers, not environment providers returned by functions like `provideHttpClient()`, `provideRouter()`, or `importProvidersFrom()`. diff --git a/adev/src/content/reference/errors/overview.md b/adev/src/content/reference/errors/overview.md index c46bf90208d1..7892d2e12439 100644 --- a/adev/src/content/reference/errors/overview.md +++ b/adev/src/content/reference/errors/overview.md @@ -8,6 +8,9 @@ | `NG0200` | [Circular Dependency in DI](errors/NG0200) | | `NG0201` | [No Provider Found](errors/NG0201) | | `NG0203` | [`inject()` must be called from an injection context](errors/NG0203) | +| `NG0204` | [Invalid Injection Token](errors/NG0204) | +| `NG0205` | [Injector has already been destroyed](errors/NG0205) | +| `NG0207` | [EnvironmentProviders in wrong context](errors/NG0207) | | `NG0209` | [Invalid multi provider](errors/NG0209) | | `NG0300` | [Selector Collision](errors/NG0300) | | `NG0301` | [Export Not Found](errors/NG0301) | diff --git a/goldens/public-api/core/errors.api.md b/goldens/public-api/core/errors.api.md index 4b59e70feea2..c46cb6dfc75c 100644 --- a/goldens/public-api/core/errors.api.md +++ b/goldens/public-api/core/errors.api.md @@ -74,7 +74,7 @@ export const enum RuntimeErrorCode { // (undocumented) INFINITE_CHANGE_DETECTION = 103, // (undocumented) - INJECTOR_ALREADY_DESTROYED = 205, + INJECTOR_ALREADY_DESTROYED = -205, // (undocumented) INVALID_APP_ID = 211, // (undocumented) @@ -90,7 +90,7 @@ export const enum RuntimeErrorCode { // (undocumented) INVALID_INHERITANCE = 903, // (undocumented) - INVALID_INJECTION_TOKEN = 204, + INVALID_INJECTION_TOKEN = -204, // (undocumented) INVALID_MULTI_PROVIDER = -209, // (undocumented) @@ -152,7 +152,7 @@ export const enum RuntimeErrorCode { // (undocumented) PROVIDED_BOTH_ZONE_AND_ZONELESS = 408, // (undocumented) - PROVIDER_IN_WRONG_CONTEXT = 207, + PROVIDER_IN_WRONG_CONTEXT = -207, // (undocumented) PROVIDER_NOT_FOUND = -201, // (undocumented) diff --git a/goldens/public-api/core/index.api.md b/goldens/public-api/core/index.api.md index 62bba7be1761..ff078f386e6b 100644 --- a/goldens/public-api/core/index.api.md +++ b/goldens/public-api/core/index.api.md @@ -84,7 +84,7 @@ export const ANIMATION_MODULE_TYPE: InjectionToken<"NoopAnimations" | "BrowserAn // @public export type AnimationCallbackEvent = { target: Element; - animationComplete: Function; + animationComplete: VoidFunction; }; // @public diff --git a/packages/common/src/directives/ng_optimized_image/lcp_image_observer.ts b/packages/common/src/directives/ng_optimized_image/lcp_image_observer.ts index 0de0e1a75734..0164e1322184 100644 --- a/packages/common/src/directives/ng_optimized_image/lcp_image_observer.ts +++ b/packages/common/src/directives/ng_optimized_image/lcp_image_observer.ts @@ -25,6 +25,7 @@ interface ObservedImageState { modified: boolean; alreadyWarnedPriority: boolean; alreadyWarnedModified: boolean; + count: number; } /** @@ -94,29 +95,77 @@ export class LCPImageObserver implements OnDestroy { registerImage(rewrittenSrc: string, isPriority: boolean) { if (!this.observer) return; - const newObservedImageState: ObservedImageState = { - priority: isPriority, - modified: false, - alreadyWarnedModified: false, - alreadyWarnedPriority: false, - }; - this.images.set(getUrl(rewrittenSrc, this.window!).href, newObservedImageState); + const url = getUrl(rewrittenSrc, this.window!).href; + const existingState = this.images.get(url); + + if (existingState) { + // If any instance has priority, the URL is considered to have priority + existingState.priority = existingState.priority || isPriority; + existingState.count++; + } else { + const newObservedImageState: ObservedImageState = { + priority: isPriority, + modified: false, + alreadyWarnedModified: false, + alreadyWarnedPriority: false, + count: 1, + }; + this.images.set(url, newObservedImageState); + } } unregisterImage(rewrittenSrc: string) { if (!this.observer) return; - this.images.delete(getUrl(rewrittenSrc, this.window!).href); + const url = getUrl(rewrittenSrc, this.window!).href; + const existingState = this.images.get(url); + + if (existingState) { + existingState.count--; + if (existingState.count <= 0) { + this.images.delete(url); + } + } } updateImage(originalSrc: string, newSrc: string) { if (!this.observer) return; const originalUrl = getUrl(originalSrc, this.window!).href; - const img = this.images.get(originalUrl); - if (img) { - img.modified = true; - this.images.set(getUrl(newSrc, this.window!).href, img); + const newUrl = getUrl(newSrc, this.window!).href; + + // URL hasn't changed + if (originalUrl === newUrl) return; + + const originalState = this.images.get(originalUrl); + if (!originalState) return; + + // Decrement count for original URL + originalState.count--; + if (originalState.count <= 0) { this.images.delete(originalUrl); } + + // Add or update entry for new URL + const newState = this.images.get(newUrl); + if (newState) { + // Merge if original had priority, new should too + newState.priority = newState.priority || originalState.priority; + newState.modified = true; + // Preserve warning flags from the original state to avoid duplicate warnings + newState.alreadyWarnedPriority = + newState.alreadyWarnedPriority || originalState.alreadyWarnedPriority; + newState.alreadyWarnedModified = + newState.alreadyWarnedModified || originalState.alreadyWarnedModified; + newState.count++; + } else { + // Create new entry, preserving state from the image that moved + this.images.set(newUrl, { + priority: originalState.priority, + modified: true, + alreadyWarnedModified: originalState.alreadyWarnedModified, + alreadyWarnedPriority: originalState.alreadyWarnedPriority, + count: 1, + }); + } } ngOnDestroy() { diff --git a/packages/core/src/animation/interfaces.ts b/packages/core/src/animation/interfaces.ts index baab333bf72c..389a1330075f 100644 --- a/packages/core/src/animation/interfaces.ts +++ b/packages/core/src/animation/interfaces.ts @@ -25,7 +25,7 @@ export const ANIMATIONS_DISABLED = new InjectionToken( * * @publicApi 20.2 */ -export type AnimationCallbackEvent = {target: Element; animationComplete: Function}; +export type AnimationCallbackEvent = {target: Element; animationComplete: VoidFunction}; /** * A [DI token](api/core/InjectionToken) that configures the maximum animation timeout diff --git a/packages/core/src/di/create_injector.ts b/packages/core/src/di/create_injector.ts index 61a7723b0190..a11b84756365 100644 --- a/packages/core/src/di/create_injector.ts +++ b/packages/core/src/di/create_injector.ts @@ -47,7 +47,10 @@ export function createInjectorWithoutInjectorInstances( scopes = new Set(), ): R3Injector { const providers = [additionalProviders || EMPTY_ARRAY, importProvidersFrom(defType)]; - name = name || (typeof defType === 'object' ? undefined : stringify(defType)); + let source: string | undefined = undefined; + if (ngDevMode) { + source = name || (typeof defType === 'object' ? undefined : stringify(defType)); + } - return new R3Injector(providers, parent || getNullInjector(), name || null, scopes); + return new R3Injector(providers, parent || getNullInjector(), source || null, scopes); } diff --git a/packages/core/src/di/forward_ref.ts b/packages/core/src/di/forward_ref.ts index d91856e4ad31..5a5c5ee25d2e 100644 --- a/packages/core/src/di/forward_ref.ts +++ b/packages/core/src/di/forward_ref.ts @@ -68,9 +68,12 @@ const __forward_ref__ = getClosureSafeProperty({__forward_ref__: getClosureSafeP */ export function forwardRef(forwardRefFn: ForwardRefFn): Type { (forwardRefFn).__forward_ref__ = forwardRef; - (forwardRefFn).toString = function () { - return stringify(this()); - }; + if (ngDevMode) { + (forwardRefFn).toString = function () { + return stringify(this()); + }; + } + return >(forwardRefFn); } diff --git a/packages/core/src/di/r3_injector.ts b/packages/core/src/di/r3_injector.ts index b06cc0404c23..bd1ea0c5a5f6 100644 --- a/packages/core/src/di/r3_injector.ts +++ b/packages/core/src/di/r3_injector.ts @@ -455,12 +455,16 @@ export class R3Injector extends EnvironmentInjector implements PrimitivesInjecto } override toString() { - const tokens: string[] = []; - const records = this.records; - for (const token of records.keys()) { - tokens.push(stringify(token)); + if (ngDevMode) { + const tokens: string[] = []; + const records = this.records; + for (const token of records.keys()) { + tokens.push(stringify(token)); + } + return `R3Injector[${tokens.join(', ')}]`; } - return `R3Injector[${tokens.join(', ')}]`; + + return 'R3Injector[...]'; } /** @@ -521,7 +525,7 @@ export class R3Injector extends EnvironmentInjector implements PrimitivesInjecto const prevConsumer = setActiveConsumer(null); try { if (record.value === CIRCULAR) { - throw cyclicDependencyError(stringify(token)); + throw cyclicDependencyError(ngDevMode ? stringify(token) : ''); } else if (record.value === NOT_YET) { record.value = CIRCULAR; diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.ts index 7403d061f017..b65f1f687782 100644 --- a/packages/core/src/errors.ts +++ b/packages/core/src/errors.ts @@ -37,9 +37,9 @@ export const enum RuntimeErrorCode { PROVIDER_NOT_FOUND = -201, INVALID_FACTORY_DEPENDENCY = 202, MISSING_INJECTION_CONTEXT = -203, - INVALID_INJECTION_TOKEN = 204, - INJECTOR_ALREADY_DESTROYED = 205, - PROVIDER_IN_WRONG_CONTEXT = 207, + INVALID_INJECTION_TOKEN = -204, + INJECTOR_ALREADY_DESTROYED = -205, + PROVIDER_IN_WRONG_CONTEXT = -207, MISSING_INJECTION_TOKEN = 208, INVALID_MULTI_PROVIDER = -209, MISSING_DOCUMENT = 210, diff --git a/packages/core/test/acceptance/destroy_ref_spec.ts b/packages/core/test/acceptance/destroy_ref_spec.ts index ce95627828dd..5f59421588db 100644 --- a/packages/core/test/acceptance/destroy_ref_spec.ts +++ b/packages/core/test/acceptance/destroy_ref_spec.ts @@ -73,7 +73,7 @@ describe('DestroyRef', () => { expect(() => { destroyRef.onDestroy(() => {}); - }).toThrowError('NG0205: Injector has already been destroyed.'); + }).toThrowError(/NG0205: Injector has already been destroyed./); }); }); diff --git a/packages/core/test/bundling/animations-standalone/bundle.golden_symbols.json b/packages/core/test/bundling/animations-standalone/bundle.golden_symbols.json index 7381ee720cd6..c962544fc4a8 100644 --- a/packages/core/test/bundling/animations-standalone/bundle.golden_symbols.json +++ b/packages/core/test/bundling/animations-standalone/bundle.golden_symbols.json @@ -830,7 +830,6 @@ "shouldBeIgnoredByZone", "shouldSearchParent", "storeLViewOnDestroy", - "stringify", "stringifyCSSSelector", "stringifyCSSSelectorList", "style", diff --git a/packages/core/test/bundling/create_component/bundle.golden_symbols.json b/packages/core/test/bundling/create_component/bundle.golden_symbols.json index c3e76b26fa04..7054c26136e5 100644 --- a/packages/core/test/bundling/create_component/bundle.golden_symbols.json +++ b/packages/core/test/bundling/create_component/bundle.golden_symbols.json @@ -686,7 +686,6 @@ "stashEventListenerImpl", "storeLViewOnDestroy", "storeListenerCleanup", - "stringify", "stringifyCSSSelector", "stringifyCSSSelectorList", "syncViewWithBlueprint", diff --git a/packages/core/test/bundling/defer/bundle.golden_symbols.json b/packages/core/test/bundling/defer/bundle.golden_symbols.json index 1cd4ce15f57e..0b7af553ee81 100644 --- a/packages/core/test/bundling/defer/bundle.golden_symbols.json +++ b/packages/core/test/bundling/defer/bundle.golden_symbols.json @@ -725,7 +725,6 @@ "shouldTriggerDeferBlock", "storeLViewOnDestroy", "storeTriggerCleanupFn", - "stringify", "stringifyCSSSelector", "stringifyCSSSelectorList", "syncViewWithBlueprint", diff --git a/packages/core/test/bundling/hydration/bundle.golden_symbols.json b/packages/core/test/bundling/hydration/bundle.golden_symbols.json index cee174e569bf..eaa7a2cbbb8a 100644 --- a/packages/core/test/bundling/hydration/bundle.golden_symbols.json +++ b/packages/core/test/bundling/hydration/bundle.golden_symbols.json @@ -775,7 +775,6 @@ "skipTextNodes", "sortAndConcatParams", "storeLViewOnDestroy", - "stringify", "stringifyCSSSelector", "stringifyCSSSelectorList", "subscribeOn", diff --git a/packages/core/test/bundling/image-directive/BUILD.bazel b/packages/core/test/bundling/image-directive/BUILD.bazel index 2a1f9db12174..e4ead4036c4d 100644 --- a/packages/core/test/bundling/image-directive/BUILD.bazel +++ b/packages/core/test/bundling/image-directive/BUILD.bazel @@ -12,6 +12,7 @@ ng_project( "e2e/image-perf-warnings-lazy/image-perf-warnings-lazy.ts", "e2e/image-perf-warnings-oversized/image-perf-warnings-oversized.ts", "e2e/image-perf-warnings-oversized/svg-no-perf-oversized-warnings.ts", + "e2e/lcp-check-duplicate/lcp-check-duplicate.ts", "e2e/lcp-check/lcp-check.ts", "e2e/oversized-image/oversized-image.ts", "e2e/preconnect-check/preconnect-check.ts", diff --git a/packages/core/test/bundling/image-directive/e2e/lcp-check-duplicate/lcp-check-duplicate.e2e-spec.ts b/packages/core/test/bundling/image-directive/e2e/lcp-check-duplicate/lcp-check-duplicate.e2e-spec.ts new file mode 100644 index 000000000000..e01ea9879aa2 --- /dev/null +++ b/packages/core/test/bundling/image-directive/e2e/lcp-check-duplicate/lcp-check-duplicate.e2e-spec.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/* tslint:disable:no-console */ +import {browser, by, element} from 'protractor'; +import {logging} from 'selenium-webdriver'; + +import {collectBrowserLogs} from '../browser-logs-util'; + +describe('NgOptimizedImage directive', () => { + it('should log a warning when a `priority` is missing on an LCP image', async () => { + await browser.get('/e2e/lcp-check-duplicate'); + // Verify that both images were rendered. + const imgs = element.all(by.css('img')); + let srcB = await imgs.get(0).getAttribute('src'); + expect(srcB.endsWith('b.png')).toBe(true); + let srcA = await imgs.get(1).getAttribute('src'); + expect(srcA.endsWith('a.png')).toBe(true); + // The `b.png` and `a.png` images are used twice in a template. + srcB = await imgs.get(2).getAttribute('src'); + expect(srcB.endsWith('b.png')).toBe(true); + srcA = await imgs.get(3).getAttribute('src'); + expect(srcA.endsWith('a.png')).toBe(true); + + // Make sure that no warnings are in the console for image `a.png`, + // since the first instance has the `priority` attribute, and is the LCP element. + const logs = await collectBrowserLogs(logging.Level.SEVERE); + expect(logs.length).toEqual(0); + }); +}); diff --git a/packages/core/test/bundling/image-directive/e2e/lcp-check-duplicate/lcp-check-duplicate.ts b/packages/core/test/bundling/image-directive/e2e/lcp-check-duplicate/lcp-check-duplicate.ts new file mode 100644 index 000000000000..d4ef8a385906 --- /dev/null +++ b/packages/core/test/bundling/image-directive/e2e/lcp-check-duplicate/lcp-check-duplicate.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {NgOptimizedImage} from '@angular/common'; +import {Component} from '@angular/core'; + +@Component({ + selector: 'lcp-check', + imports: [NgOptimizedImage], + template: ` + + + +
+ + + + +
+ + + + + + + +
+ `, +}) +export class LcpCheckDuplicate {} diff --git a/packages/core/test/bundling/image-directive/e2e/oversized-image/oversized-image.e2e-spec.ts b/packages/core/test/bundling/image-directive/e2e/oversized-image/oversized-image.e2e-spec.ts index 4f396b04aeba..bf4fce9c2dee 100644 --- a/packages/core/test/bundling/image-directive/e2e/oversized-image/oversized-image.e2e-spec.ts +++ b/packages/core/test/bundling/image-directive/e2e/oversized-image/oversized-image.e2e-spec.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.dev/license */ -import {browser, by, element, ExpectedConditions} from 'protractor'; +import {browser} from 'protractor'; import {logging} from 'selenium-webdriver'; import {collectBrowserLogs} from '../browser-logs-util'; diff --git a/packages/core/test/bundling/image-directive/index.ts b/packages/core/test/bundling/image-directive/index.ts index 639db0294d2e..98b79b8c8cdb 100644 --- a/packages/core/test/bundling/image-directive/index.ts +++ b/packages/core/test/bundling/image-directive/index.ts @@ -27,6 +27,7 @@ import { } from './e2e/oversized-image/oversized-image'; import {PreconnectCheckComponent} from './e2e/preconnect-check/preconnect-check'; import {PlaygroundComponent} from './playground'; +import {LcpCheckDuplicate} from './e2e/lcp-check-duplicate/lcp-check-duplicate'; @Component({ selector: 'app-root', @@ -42,6 +43,7 @@ const ROUTES = [ // Paths below are used for e2e testing: {path: 'e2e/basic', component: BasicComponent}, {path: 'e2e/lcp-check', component: LcpCheckComponent}, + {path: 'e2e/lcp-check-duplicate', component: LcpCheckDuplicate}, {path: 'e2e/image-perf-warnings-lazy', component: ImagePerfWarningsLazyComponent}, {path: 'e2e/image-perf-warnings-oversized', component: ImagePerfWarningsOversizedComponent}, {path: 'e2e/svg-no-perf-oversized-warnings', component: SvgNoOversizedPerfWarningsComponent}, diff --git a/packages/core/test/bundling/standalone_bootstrap/bundle.golden_symbols.json b/packages/core/test/bundling/standalone_bootstrap/bundle.golden_symbols.json index db9a26025e96..ec848cf8a5c3 100644 --- a/packages/core/test/bundling/standalone_bootstrap/bundle.golden_symbols.json +++ b/packages/core/test/bundling/standalone_bootstrap/bundle.golden_symbols.json @@ -612,7 +612,6 @@ "shouldBeIgnoredByZone", "shouldSearchParent", "storeLViewOnDestroy", - "stringify", "stringifyCSSSelector", "stringifyCSSSelectorList", "syncViewWithBlueprint", diff --git a/packages/core/test/di/r3_injector_spec.ts b/packages/core/test/di/r3_injector_spec.ts index c1aba322548b..e02830580e72 100644 --- a/packages/core/test/di/r3_injector_spec.ts +++ b/packages/core/test/di/r3_injector_spec.ts @@ -15,10 +15,10 @@ import { ɵɵdefineInjector, ɵɵinject, } from '../../src/core'; -import {ERROR_DETAILS_PAGE_BASE_URL} from '../../src/error_details_base_url'; import {createInjector} from '../../src/di/create_injector'; import {InternalInjectFlags} from '../../src/di/interface/injector'; import {R3Injector} from '../../src/di/r3_injector'; +import {ERROR_DETAILS_PAGE_BASE_URL} from '../../src/error_details_base_url'; describe('InjectorDef-based createInjector()', () => { class CircularA { @@ -461,14 +461,14 @@ describe('InjectorDef-based createInjector()', () => { it('does not allow injection after destroy', () => { (injector as R3Injector).destroy(); expect(() => injector.get(DeepService)).toThrowError( - 'NG0205: Injector has already been destroyed.', + /NG0205: Injector has already been destroyed./, ); }); it('does not allow double destroy', () => { (injector as R3Injector).destroy(); expect(() => (injector as R3Injector).destroy()).toThrowError( - 'NG0205: Injector has already been destroyed.', + /NG0205: Injector has already been destroyed./, ); }); @@ -506,7 +506,7 @@ describe('InjectorDef-based createInjector()', () => { static ɵinj = ɵɵdefineInjector({providers: [MissingArgumentType]}); } expect(() => createInjector(ErrorModule).get(MissingArgumentType)).toThrowError( - "NG0204: Can't resolve all parameters for MissingArgumentType: (?).", + /NG0204: Can't resolve all parameters for MissingArgumentType: \(\?\)./, ); }); }); diff --git a/packages/core/test/linker/ng_module_integration_spec.ts b/packages/core/test/linker/ng_module_integration_spec.ts index 5680166765bc..3557f027ac98 100644 --- a/packages/core/test/linker/ng_module_integration_spec.ts +++ b/packages/core/test/linker/ng_module_integration_spec.ts @@ -33,13 +33,13 @@ import {NgModuleType} from '../../src/render3'; import {getNgModuleDef} from '../../src/render3/def_getters'; import {ComponentFixture, inject, TestBed} from '../../testing'; +import {ERROR_DETAILS_PAGE_BASE_URL} from '../../src/error_details_base_url'; import {InternalNgModuleRef, NgModuleFactory} from '../../src/linker/ng_module_factory'; import { clearModulesForTest, setAllowDuplicateNgModuleIdsForTest, } from '../../src/linker/ng_module_registration'; import {stringify} from '../../src/util/stringify'; -import {ERROR_DETAILS_PAGE_BASE_URL} from '../../src/error_details_base_url'; class Engine {} @@ -542,7 +542,7 @@ describe('NgModule', () => { it('should throw when no type and not @Inject (class case)', () => { expect(() => createInjector([NoAnnotations])).toThrowError( - "NG0204: Can't resolve all parameters for NoAnnotations: (?).", + /NG0204: Can't resolve all parameters for NoAnnotations: \(\?\)./, ); }); diff --git a/packages/forms/signals/src/util/parser.ts b/packages/forms/signals/src/util/parser.ts index b32fc5945028..01c3c05569f1 100644 --- a/packages/forms/signals/src/util/parser.ts +++ b/packages/forms/signals/src/util/parser.ts @@ -44,10 +44,12 @@ export function createParser( const setRawValue = (rawValue: TRaw) => { const result = parse(rawValue); - errors.set(result.errors ?? []); if (result.value !== undefined) { setValue(result.value); } + // `errors` is a linked signal sourced from the model value; write parse errors after + // model updates so `{value, errors}` results do not get reset by the recomputation. + errors.set(result.errors ?? []); }; return {errors: errors.asReadonly(), setRawValue}; diff --git a/packages/forms/signals/test/node/parse_errors.spec.ts b/packages/forms/signals/test/node/parse_errors.spec.ts index 6b650fe98f4b..010e40204e46 100644 --- a/packages/forms/signals/test/node/parse_errors.spec.ts +++ b/packages/forms/signals/test/node/parse_errors.spec.ts @@ -11,6 +11,7 @@ import {TestBed} from '@angular/core/testing'; import { form, FormField, + maxError, transformedValue, validate, type FormValueControl, @@ -304,6 +305,25 @@ describe('parse errors', () => { expect(errors1).toEqual([]); expect(input1.value).toBe('42'); }); + + it('should preserve parse errors when transformedValue parse returns both value and errors', async () => { + @Component({ + imports: [TestNumberInput, FormField], + template: ``, + }) + class TestCmp { + state = signal(5); + f = form(this.state); + } + + const fix = await act(() => TestBed.createComponent(TestCmp)); + const comp = fix.componentInstance; + const input: HTMLInputElement = fix.nativeElement.querySelector('input')!; + + input.value = '11'; + await act(() => input.dispatchEvent(new Event('input'))); + expect(comp.f().errors()).toEqual([jasmine.objectContaining({kind: 'max'})]); + }); }); @Component({ @@ -318,6 +338,7 @@ describe('parse errors', () => { class TestNumberInput implements FormValueControl { readonly value = model.required(); readonly errors = input([]); + readonly parseMax = input(undefined); protected readonly rawValue = transformedValue(this.value, { parse: (rawValue) => { @@ -326,6 +347,9 @@ class TestNumberInput implements FormValueControl { if (Number.isNaN(value)) { return {errors: [{kind: 'parse', message: `${rawValue} is not numeric`}]}; } + if (this.parseMax() != null && value > this.parseMax()!) { + return {value, errors: [maxError(this.parseMax()!)]}; + } return {value}; }, format: (value) => {