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 中编写这样的提供程序(或视图提供程序),从它的模板/视图中提供可注入的对象?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...