简体   繁体   English

Angular ContentChild 始终未使用注入令牌定义

[英]Angular ContentChild is always undefined using injection token

I'm trying to implement a bridge pattern for content projection.我正在尝试为内容投影实现桥接模式。 In the component that has the ng-content tag in the HTML, I tried to get it via this line, where BUTTON_ENABLED_DIALOG is an InjectionToken :在 HTML 中具有ng-content标签的组件中,我尝试通过这一行获取它,其中BUTTON_ENABLED_DIALOGInjectionToken

@ContentChild(BUTTON_ENABLED_DIALOG, {static: true}) content?: IButtonEnabledDialog

The calling component does add BUTTON_ENABLED_DIALOG to the providers array.调用组件确实将BUTTON_ENABLED_DIALOG添加到提供程序数组。

That value is never getting set, even though I see the content.即使我看到内容,该值也永远不会设置。 A tiny StackBlitz example can be found at https://stackblitz.com/edit/angular-ivy-pgnuny?file=src/app/app.component.ts可以在https://stackblitz.com/edit/angular-ivy-pgnuny?file=src/app/app.component.ts找到一个小的 StackBlitz 示例

You have a wrong usage of @ContentChild decorator here.您在这里错误地使用了@ContentChild装饰器。 It can be used in the upper level of projected element to get access to the projected content, - within the AppComponent in your example.它可以用于投影元素的上层以访问投影内容,在您的示例中的AppComponent中。

For your purpose you can just use the Dependency Injection :出于您的目的,您可以只使用Dependency Injection

export class ButtonEnabledDialogComponent implements AfterViewInit {
  constructor(@Inject(BUTTON_ENABLED_DIALOG) private content: IButtonEnabledDialog
) {} 

And get access to your injection token.并访问您的注入令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM