css - 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 时,我是否可以使用其中一个生命周期函数或以另一种方式选择父级?
解决方案
我想到了。我必须在图像上添加一个模板标签,然后用ViewChildren
type抓取它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';
});
}
}
推荐阅读
- c++ - DirectX11 - 具有流输出的几何着色器
- amazon-web-services - S3 存储桶的 Route53 子域别名
- javascript - 当上面的元素切换可见/不可见时保持滚动位置
- android - 您真的需要在停止之前检查 MediaPlayer 是否正在运行吗?
- ruby - 为什么 Ruby 会出现错误?
- javascript - 如何在 JavaScript 中获取 JSON 数据数组?
- github - 你如何建议对 Github 中的 repo 描述进行编辑
- javascript - 带有 HTML 和 PHP 的动态表
- jquery - 如何强制白色背景中的元素覆盖其他元素?
- c# - NotifyIcon 点击事件在表单停用之后触发