angularangular-signalsangular-effect

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());
    });
  }
}

Solution

  • Where it can be

    As per the documentation, by default, you can only create an effect() within 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});
    

    Where it should be

    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.