javascript - 嵌套 Angular 结构指令的 ContentChild 未定义
问题描述
我有一个结构指令 A 嵌套在另一个结构指令 B 中。现在我想访问 A 内部的 B 以使用它的 templateRef。
我尝试使用 ContentChild,但它始终未定义。有人可以告诉我必须改变什么才能获得访问权限吗?
我在 StackBlitz 中重新创建了我的星座:https ://stackblitz.com/edit/angular-b697ct?file=src%2Fapp%2Fhello.component.ts
指令定义:
@Directive({selector: '[testChild]'})
export class B {
}
@Directive({selector: '[testParent]'})
export class A {
@ContentChild(B, {static: false}) contentTemplate: B;
constructor(public viewContainer: ViewContainerRef, public templateRef: TemplateRef<any>) {
}
ngAfterViewInit() {
console.log(this.contentTemplate); // logs undefined
}
}
@Directive({selector: '[tstOutlet]'})
export class TestOutlet {
constructor(public viewContainer: ViewContainerRef) {
}
}
@Component({
selector: 'tst',
template: `<ng-container tstOutlet></ng-container>`,
})
export class HelloComponent implements AfterViewInit {
@ContentChildren(A) parents: QueryList<A>;
@ViewChild(TestOutlet, {static: true}) outlet: TestOutlet;
ngAfterViewInit() {
this.parents.toArray().forEach((parent: A) => {
this.outlet.viewContainer.createEmbeddedView(parent.templateRef);
});
}
}
模板定义:
<tst>
<ng-container *testParent>
<span *testChild>Test</span>
</ng-container>
<ng-container *testParent>
<span *testChild>Second Test</span>
</ng-container>
</tst>
解决方案
推荐阅读
- java - 从 recursion 返回时对象值的状态
- asp.net-mvc - ASP.Net 身份与 SAML 集成
- vba - 连接 Azure Databricks - VBA
- java - Android studio:如何正确导入可以在我的项目中导入的第三方代码?
- android - 带蓝牙的安卓模拟器
- javascript - 如何在弹出窗口中一一显示输入中的表单验证错误?
- c# - 使用winform图表创建二进制直方图时的问题
- wordpress - WooCommerce 中缺少“购物车”页面内容
- python - 使用 TFlite 启用 Dropout
- amazon-web-services - 带有 VPC 负载均衡器的 AWS API 网关重定向到不正确的路径(前缀未省略)