Recently I had a task where I needed to pass a TemplateRef to component, which provides some service, say SomeService. And inside that template I used a directive that injects service SomeService. I ended up with NullInjectorError.
So my question is how can I get service provided in component but not inside ViewContent.
Here is minimal representation of what I'm trying to do. Let's assume that all components and directives are declared in the same module.
root-component. All that's happening here is that I'm passing a template reference to the app-component and use the directive inside template.
@Component({
selector: 'root-component',
template: `
<app-component [itemTemplate]="template"></app-component>
<ng-template #template >
<div testDirective>hello</div>
</ng-template>
`
})
export class RootComponent {
}
app-component. Here I provide SomeService
@Component({
selector: 'app-component',
template: `
<ng-container [ngTemplateOutlet]="itemTemplate"></ng-container>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
SomeService // <-- HERE IS THE SERVICE THAT I'M TRYING TO INJECT INTO DIRECTIVE
],
})
export class AppComponent {
@Input()
itemTemplate: TemplateRef<unknown> | null = null;
constructor(
) {
}
}
testDirective
@Directive({
selector: '[testDirective]'
})
export class TestDirective {
constructor(
private _someService: SomeService // <-- THIS CAUSE AN NullInjectorError
) {
}
}
There is no need to show the implementation of SomeService as it is just a regular service.
I apologize if something is not clear, this is my first question on StackOverflow