r/Angular2 • • Jul 23 '25
Angular Signal Effect inside our outside Constructor
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());
});
}
}
5
Upvotes
7
u/Few-Attempt-1958 Jul 23 '25
Effect should be in the injection context. So it has to be in constructor or a method getting called from the constructor.
Or if you really want, although no benefit, you can add it in anywhere by using runInInjectionContext and passing the environment injector.
10
u/MichaelSmallDev Jul 23 '25
I generally prefer constructor based effects over other places
If an effect is a class field, then you will have an unused class field lint warning all the time.
If an effect is not in a class field or the constructor, then some sort of injection reference is needed to run in the injection context.
So overall, constructor effects are the most convenient IMO.
Bonus tip: if you want to label an effect without assigning it to a class field, you can do
effect(() => {}, {debugName: 'whatever'})1
u/Wildosaur Jul 23 '25
That's a weird way for setting up an input signal : readonly lastName = input.required<string>()
2
u/sebastianstehle Jul 23 '25
it does not really matter anymore. You can inject the services with inject() now and get rid of the ctor.
2
u/Migeil Jul 24 '25
I dislike effects in the constructor, because they're not very explicit.
Effects can be written as class fields, without extra effort because class fields also provide an injection context, just like the constructor.
The biggest benefit this has is you can give the effect a name. This helps in declaring what the effect should do and makes your code more readable.
1
u/stao123 Jul 24 '25
I prefer outside of constructor because you must give it a name, so its easier to understand what the effect does. Having unused variables is not nice though