💻 Tech
effect() requires an injection context. If used within the constructor, it uses the injection context of the component. One reason it needs an injection context is for when Angular destroys resources, letting Angular know te dependencies. The error below shows when effect() is used without implicit or explicit injection context.
ERROR RuntimeError: NG0203: effect() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more at https://angular.dev/errors/NG0203
Example of using effect() with and without injection context
ctr = signal(0);
constructor() {
// Uses implicit injection context provided by Angular's dependency injection context; not causing error
effect(() => {
console.log(`Counter: ${this.ctr()}`);
});
// Causes the NG0203 error
afterNextRender(() => {
effect(() => {
console.log(`Counter: ${this.ctr()}`);
});
});
}
If you need to use effect() outside the injection context, you need to manually address the dependencies by creating an instance of the Injector and providing it to effect() like the example below:
injector = inject(Injector);
constructor() {
afterNextRender(() => {
effect(
() => {
console.log(`Counter: ${this.ctr()}`);
},
{
injector: this.injector,
}
);
});
}