Does Angular have any guidance where I should put the Effect code? Is it generally inside Constructor or outside? What are the advantages / disadvantages for each method?
export class CustomerForm {
lastName= input.required<string>();
constructor() {
effect(() => {
console.log('lastName changed:', this.lastName());
});
}
}
As per the documentation, by default, you can only create an effect()
within an injection context:
During construction (via the constructor
) of a class being instantiated by the DI system, such as an @Injectable
or @Component
.
In the initializer for fields of such classes.
In the factory function specified for useFactory
of a Provider
or an @Injectable
.
In the factory
function specified for an InjectionToken
.
Within a stack frame that runs in an injection context.
But if you need to create an effect()
outside of the constructor, you can pass an Injector
via its options:
effect(() => {
console.log(`The count is: ${this.count()}`);
}, {injector: this.injector});
If we look at how effect()
has been implemented so far (July 2025) in the official Angular Material components, we find out that it's systematically called in the constructor or a private method called by the constructor.
It is the commonly accepted place for effects. That pattern should be followed to increase your code readability, unless there's a good reason not to.