【问题标题】:How do I access DOM elements of an embedded template? (Angular 11)如何访问嵌入模板的 DOM 元素? (角度 11)
【发布时间】:2021-05-28 05:51:25
【问题描述】:

上下文

我有两个 Angular 组件,一个父组件和一个子组件。父级将可选的<ng-template> TemplateRef 作为@Input 传递给子级。如果没有给出输入,则子级要么呈现此模板,要么呈现其默认模板。

parent.component.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)ContentChild('container) 访问该元素,它会在 customTemplate 上返回 undefined 但返回正确的元素引用默认。

无论模板是作为@Input 传入还是我们使用默认模板,我如何访问这些嵌入的DOM 元素?

查看下面的 Stackblitz 示例,了解我正在努力实现的目标。希望它是不言自明的。

Stackblitz Example with full project

【问题讨论】:

    标签: javascript angular dom angular2-template viewchild


    【解决方案1】:

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

    My solution on stackblitz

    app.componen.ts

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

    【讨论】:

    • 感谢您的回答!这只是显示模板内的宽度。我无权访问子组件中的元素,是吗?如果我想用该值进行某种形式的计算怎么办?或者如果我根本不想显示它而只想将它保存为变量怎么办?
    猜你喜欢
    • 2018-10-14
    • 2019-04-08
    • 2015-10-31
    • 2019-08-07
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多