最近我有一个任务,我需要将一个TemplateRef
传递给组件,它提供一些服务,比如SomeService.在该模板中,我使用了注入服务SomeService的指令.我最终得到了NullInjectorError
分.
所以我的问题是,如何在组件中提供服务,而不是在ViewContent中提供服务.
以下是我正在try 做的事情的最低限度的表示.让我们假设所有组件和指令都在同一个模块中声明.
根组件.这里发生的所有事情是,我将一个模板引用传递给app-Component,并在模板中使用指令.
@Component({
selector: 'root-component',
template: `
<app-component [itemTemplate]="template"></app-component>
<ng-template #template >
<div 测试指令>hello</div>
</ng-template>
`
})
export class RootComponent {
}
应用程序组件.在这里,我提供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(
) {
}
}
测试指令
@Directive({
selector: '[测试指令]'
})
export class TestDirective {
constructor(
private _someService: SomeService // <-- THIS CAUSE AN NullInjectorError
) {
}
}
没有必要展示SomeService
的实施情况,因为这只是一项常规服务.
如果有不清楚的地方,我很抱歉,这是我在StackOverflow上的第一个问题