angular - 如何将模板从Angular中的子组件传递给父级
问题描述
我有这样的角度布局,我想从子组件更改父组件中的 Header 部分。
我用谷歌搜索了这个问题,但我只看到有关将模板从父组件传递到子组件的文章。
有没有办法将模板从子组件传递给父组件?
或者有什么方法可以将组件从子组件注入到父组件的标题部分?
我知道我可以将值传递给父级,但我需要传递模板或组件。
解决方案
从架构的角度来看,这个想法不是很好,考虑到一些组件应该如何影响其他组件、从根到叶的数据流和角度变化检测。但这仍然是可能的
// 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 时,角度的变化检测性质已经在父组件上完成了变化检测。
推荐阅读
- class - 在 typescript 中扩展 Request 编译为带有 TypeError 的 ES5
- ios - UIImagePickerController videoMaximumDuration 不起作用
- sql - DB2 SQL 列到行
- javascript - Tui 图表依赖缺失?
- r - !str_detect(col, pattern) 从 data.frame 中删除的行多于 str_detect(col, pattern)
- arduino - 无法将程序上传到 ESP8266
- html - 将 div 居中在 2 个 div 上的 CSS 指南
- python - python instance() 或 type() 无法得到正确的结果
- ios - 删除 UIBezierPath 上的额外空间
- angular - 错误 无法加载 PDF 文档。(角5)