首页 > 解决方案 > 如何将模板从Angular中的子组件传递给父级

问题描述

我有这样的角度布局,我想从子组件更改父组件中的 Header 部分。 在此处输入图像描述

我用谷歌搜索了这个问题,但我只看到有关将模板从父组件传递到子组件的文章。

有没有办法将模板从子组件传递给父组件?

或者有什么方法可以将组件从子组件注入到父组件的标题部分?

我知道我可以将值传递给父级,但我需要传递模板或组件。

标签: angular

解决方案


从架构的角度来看,这个想法不是很好,考虑到一些组件应该如何影响其他组件、从根到叶的数据流和角度变化检测。但这仍然是可能的

// parent.ts
setHeaderTemplate(templateRef: TemplateRef) {
  this.headerTemplate = templateRef
}
// parent.html
<div *ngTemplateOutlet="template">
</div>
// child.ts
@ViewChild(TemplateRef) headerTpl: TemplateRef;
constructor(private parent: ParentComponent) {}

ngAfterViewInit() {
  Promise.resolve().then(() => this.parent.showHeaderTemplate(this.headerTpl));
}
// child.html
<ng-template #header>
  hello header
</ng-template>

请注意,在子级中“显示”模板逻辑是在异步代码中完成的。这是因为在评估 ngAfterViewInit 时,角度的变化检测性质已经在父组件上完成了变化检测。


推荐阅读