首页 > 解决方案 > Angular9在使用ng-container和ngIf添加的元素上获取父节点

问题描述

我试图在添加 ng-template 时获取父元素ngIf

布局:

<section>
  <h2>
    Hello!
    <ng-container *ngIf="someCondition1; then myTemplate"></ng-container>
  </h2>

  <div>
    Another one!
    <ng-container *ngIf="someCondition2; then myTemplate"></ng-container>
  </div>

  <!-- More markup here that show myTemplate based on conditions -->
</section>

<ng-template #myTemplate>
  <img src="path/to/image.png" />
</ng-template>

以上工作正常,但我想抓住它添加的任何地方的父元素,并将一些样式应用于打字稿文件中的父元素。每当将模板添加到 DOM 时,我是否可以使用其中一个生命周期函数或以另一种方式选择父级?

标签: cssangulardom

解决方案


我想到了。我必须在图像上添加一个模板标签,然后用ViewChildrentype抓取它QueryList。这使我可以访问每个可以获取父节点的本地元素。这必须在AfterViewInit生命周期挂钩中完成。

HTML:

<section>
  <h2>
    Hello!
    <ng-container *ngIf="someCondition1; then myTemplate"></ng-container>
  </h2>

  <!-- More markup here that show myTemplate based on conditions -->
</section>

<ng-template #myTemplate>
  <img #myTemplateImage src="path/to/image.png" />
</ng-template>

打字稿:

import { Component, ViewChildren, ElementRef, QueryList, AfterViewInit } from '@angular/core';

@Component({
  selector: 'test-selector',
  templateUrl: './test.component.html'
})
export class TestComponent implements AfterViewInit {
  @ViewChildren('myTemplateImage') imageList: QueryList<ElementRef>;

  ngAfterViewInit() {
    this.imageList.forEach((item) => {
      item.nativeElement.parentNode.style.fontStyle = 'italic';
    });
  }
}

推荐阅读