angular - Angular - 内容提供者
问题描述
是否可以将提供者从视图组件“传递”到内容组件?
我一遍又一遍地面临这个问题,既找不到解决方案,也找不到设计上不可能的信息(文档)。
如果我在模板中有一个组件,则可以将其注入子组件的构造函数中(这当然可以):
@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 中编写这样的提供程序(或 viewProvider),从它的模板/视图中提供可注入对象?
解决方案
推荐阅读
- c# - 使用 svcutil 从简单的 xml 文件生成 C# 类
- sql - 我一直在尝试将特定数据插入我的数据库
- java - Java - ExecutorService 取消开销
- entity-framework - 在需要父级但不是两者的实体框架子级上级联删除
- line - 如何将星号添加到文件名列表中,然后使用 Notepad++ 使其成为一行
- vba - Powerpoint 宏不适用于幻灯片
- javascript - 如何在没有 MongoDB 的情况下通过 Galaxy 部署 Meteor.js 应用程序?
- r - 无法在 R 中存储循环输出
- amazon-web-services - 在 Amazon Workspaces 上运行 Vagrant
- python - 在 POSTGRESQL 中不使用 array_agg() 将数据复制到数组中