angularangular-signals

use effect and afterNextRender together


I have a signal effect that I want to run only in the browser (and nothing in the server)

but both effect and afterNextRender require being run from the injection context

so running this code

effect(() => {
  afterNextRender(() => {
    // ...
  });
});

throw ERROR Error: NG0203: afterNextRender() 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.io/errors/NG0203

and running

afterNextRender(() => {
  effect(() => {
    // ...
  });
});

throw ERROR Error: 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.io/errors/NG0203


Solution

  • the other answer is the correct answer with Angular 19 or earlier

    now with Angular 20 there is afterRenderEffect that can do that in one step

    I decided to write it down as an answer since the other answer owner is not active and can't update it