← Back to list

Using effect in ngOnInit

In Angular, the effect method is typically limited to use within the constructor. However, there are times when we may want to use it…

Ruso · 2024-11-02 20:46 · 3 claps · 1.0 min read
#angular-effects #using-signals-in-angular #dependency-injection #lifecycle-hook #angular-performance-tips
Open on Medium ↗
Wiki topics: 🌐 · Web Development

Using effect in ngOnInit

In Angular, the **effect method is typically limited to use within the constructor. However, there are times when we may want to use it inside the `ngOnInit**lifecycle hook—particularly if we’re waiting for data to be loaded or initialized before applying the effect. Attempting to useeffect` directly in **ngOnInit will cause an error because `ngOnInit` **does not automatically provide the necessary injection context.

import { Component, OnInit, inject, Injector, runInInjectionContext, effect } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {

  private injector: Injector = inject(Injector); // Define injector instance

  ngOnInit(): void {
    // Using runInInjectionContext to provide the necessary context
    runInInjectionContext(this.injector, (): void => {
      effect((): void => {
        console.log("Effect is running inside ngOnInit!");
      });
    });
  }
}

If you use a signal within an **effect, simply adding `{ allowSignalWrites: true }`** is sufficient.

import { Component, OnInit, inject, Injector, runInInjectionContext, effect,signal, WritableSignal } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {

  private injector: Injector = inject(Injector); // Define injector instance
  public count: WritableSignal<number> = signal(0);

  ngOnInit(): void {
    // Using runInInjectionContext to provide the necessary context
    runInInjectionContext(this.injector, (): void => {
      effect((): void => {
        console.log("Effect is running inside ngOnInit!");
        this.count.set(1)
        console.log(`Count is ${this.count()}`);
      },{ allowSignalWrites: true });
    });
  }
}

메타데이터
post_id
33049fe210ff
slug
using-effect-in-ngoninit-33049fe210ff
url
https://medium.com/@developers93/using-effect-in-ngoninit-33049fe210ff
canonical_url
https://medium.com/@developers93/using-effect-in-ngoninit-33049fe210ff
author_url
https://medium.com/@developers93
status
ok
fetched_at
2026-07-22 04:22:49