首页 > 解决方案 > 如何访问嵌入模板的 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,了解我正在尝试完成的示例。希望它是不言自明的。

带有完整项目的 Stackblitz 示例

标签: javascriptangulardomangular2-templateviewchild

解决方案


我修改了代码,我只使用了一个子组件,而不是像你的例子那样的两个,在我的解决方案中,我使用三元运算符来决定我需要渲染哪个模板。

我在 stackblitz 上的解决方案

app.componen.ts

<!-- Call to Child Component -->
<div class="childComponent">
  <child [customTemplate]="displayCustom ? parentTemplate : null"></child>
</div>

推荐阅读