首页 > 解决方案 > 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),从它的模板/视图中提供可注入对象?

标签: angularangular-providersng-contentangular-injector

解决方案


推荐阅读