javascript - 如何访问嵌入模板的 DOM 元素?(角度 11)
问题描述
语境
我有两个 Angular 组件,一个父级和一个子级。父级将可选的<ng-template>
TemplateRef 作为@Input
. 然后,如果没有给出输入,孩子要么呈现这个模板,要么呈现它的默认模板。
父组件.html
// Pass in template as @Input
<child [customTemplate]="parentTemplate"></child>
// Define Custome Template
<ng-template #parentTemplate>
<div #container class="container">HELLO FROM CUSTOM CONTAINER</div>
</ng-template>
child.component.html
// Render correct template
<ng-container *ngTemplateOutlet="customTemplate || defaultTemplate;">
</ng-container>
// Define default template
<ng-template #defaultTemplate>
<div #container class="container">HELLO FROM DEFAULT CONTAINER</div>
</ng-template>
child.component.ts
export class ChildComponent implements AfterViewInit {
@Input() public customTemplate!: TemplateRef<HTMLElement>
@ViewChild("container")
containerRef!: ElementRef;
ngAfterViewInit() {
console.log(this.containerRef?.nativeElement.offsetWidth)
}
}
问题
我希望能够访问由我的子组件呈现的 DOM 元素。例如,假设我想查找当前呈现在屏幕上的 HTML 元素的宽度。
如果我在 customTemplate 和 defaultTemplate 中都定义了一个模板变量#container
,然后尝试使用@ViewChild('container)
or访问该元素ContentChild('container)
,它会在 customTemplate 上返回 undefined 但返回正确的元素引用和默认值。
我如何访问这些嵌入的 DOM 元素,无论模板是作为 an 传入@Input
还是我们使用默认值?
查看下面的 Stackblitz,了解我正在尝试完成的示例。希望它是不言自明的。
解决方案
我修改了代码,我只使用了一个子组件,而不是像你的例子那样的两个,在我的解决方案中,我使用三元运算符来决定我需要渲染哪个模板。
app.componen.ts
<!-- Call to Child Component -->
<div class="childComponent">
<child [customTemplate]="displayCustom ? parentTemplate : null"></child>
</div>
推荐阅读
- python - 如何使用pytest测试处理请求的Flask(非路由)函数?
- angular - 从 Angular html ionic 应用程序访问资产包中的图像文件
- python - python:使用请求模块保持HTTP连接打开
- r - R Shiny 响应式/动态分配对象名称
- loops - Pentaho 数据集成循环计数变量
- kotlin - 将库测试中的测试接口导入应用程序的测试
- javascript - 我可以将用户纬度保存到变量吗?
- javascript - 赠品获胜者未定义
- swift - 从视图外的函数访问@StateObject
- android - IllegalArgumentException:无法从当前目的地 Destination [Navigation Error] 找到导航操作/目的地