[英]Angular ContentChild is always undefined using injection token
我正在嘗試為內容投影實現橋接模式。 在 HTML 中具有ng-content
標簽的組件中,我嘗試通過這一行獲取它,其中BUTTON_ENABLED_DIALOG
是InjectionToken
:
@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.