簡體   English   中英

Angular ContentChild 始終未使用注入令牌定義

[英]Angular ContentChild is always undefined using injection token

我正在嘗試為內容投影實現橋接模式。 在 HTML 中具有ng-content標簽的組件中,我嘗試通過這一行獲取它,其中BUTTON_ENABLED_DIALOGInjectionToken

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

調用組件確實將BUTTON_ENABLED_DIALOG添加到提供程序數組。

即使我看到內容,該值也永遠不會設置。 可以在https://stackblitz.com/edit/angular-ivy-pgnuny?file=src/app/app.component.ts找到一個小的 StackBlitz 示例

您在這里錯誤地使用了@ContentChild裝飾器。 它可以用於投影元素的上層以訪問投影內容,在您的示例中的AppComponent中。

出於您的目的,您可以只使用Dependency Injection

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

並訪問您的注入令牌。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM