是否可以将提供者从视图组件“传递”到内容组件?
我一遍又一遍地面临这个问题,既找不到解决方案,也找不到设计无法实现的信息(文档)。
如果我在模板中有一个组件,它可以被注入到子组件的构造函数中(这当然有效):
@Component({
selector: 'aaa',
template: '<div>This is AAA {{prop}}><div><ng-content></ng-content></div>'
})
export class AComponent {
prop = Math.random();
}
@Component({
selector: 'bbb',
template: '<div>This is BBB. Parent is AAA {{a.prop}}</div>'
})
export class BComponent {
constructor(public a: AComponent) { }
}
<aaa><bbb></bbb></aaa>
结果:
This is AAA 0.4997284193879621>
This is BBB. Parent is AAA 0.4997284193879621
但是如果我要注入的组件是其他组件视图的一部分,是否可以实现这一点?
这种情况不起作用:
@Component({
selector: 'ccc',
template: '<aaa><ng-content></ng-content></aaa>'
})
export class CComponent {
}
<ccc><bbb></bbb></ccc>
以 NullInjectorError: R3InjectorError(AppModule)[AComponent -> AComponent -> AComponent]: NullInjectorError: No provider for AComponent!
结尾
有没有办法在 CComponent 中编写这样的提供程序(或视图提供程序),从它的模板/视图中提供可注入的对象?