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`).
```ts
import {Injectable, inject, EnvironmentInjector, runInInjectionContext} from '@angular/core';
@Injectable({providedIn: 'root'})
export class MyService {
private injector = inject(EnvironmentInjector);
doSomethingDynamic() {
runInInjectionContext(this.injector, () => {
// ✅ Now valid to use inject() here
const router = inject(Router);
});
}
}
```
## `assertInInjectionContext`
Use `assertInInjectionContext` in utility functions to guarantee they are called from a valid context. It throws a clear error if not.
```ts
import {assertInInjectionContext, inject, ElementRef} from '@angular/core';
export function injectNativeElement<TextendsElement>(): T {