Created
February 20, 2025 07:48
-
-
Save Armenvardanyan95/728806db1b9701047705fe11ca6eda7d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Injectable() | |
export class SomeService { | |
data = 10; | |
updateData() { | |
this.data = 20; | |
} | |
} | |
@Component({ | |
selector: 'app-di-child', | |
template: `{{someService.data}}`, | |
// `SomeService` is only provided here | |
providers: [SomeService] | |
}) | |
export class DiChildComponent { | |
someService = inject(SomeService); | |
} | |
@Component({ | |
selector: 'app-di-parent', | |
template: ` | |
<app-di-child/> | |
`, | |
imports: [DiChildComponent], | |
// here `SomeService` is NOT provided, so we might | |
}) | |
export class DiParentComponent implements OnInit { | |
child = viewChild.required(DiChildComponent, {read: ViewContainerRef}); | |
someService!: SomeService; | |
// we can't do `someService = inject(SomeService);` | |
// here, because `SomeService` is not provided in this component | |
ngOnInit() { | |
// instead, we can use the injection context of the child component | |
this.someService = runInInjectionContext( | |
this.child().injector, | |
// and inject `SomeService` in that context, where it is provided | |
() => inject(SomeService), | |
); | |
this.someService.updateData(); | |
// after this, the template of `DiChildComponent` will show `20` | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment