Sitemap
Press enter or click to view image in full size

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 use effect directly in ngOnInit will cause an error because ngOnInit does not automatically provide the necessary injection context.

Get Ruso’s stories in your inbox

Join Medium for free to get updates from this writer.

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

--

--

Ruso
Ruso

Written by Ruso

0 followers

Laravel programmer