[英]Angular9 get parent node on element added with ng-container and ngIf
當使用ngIf
添加 ng-template 時,我試圖獲取父元素。
布局:
<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>
以上工作正常,但我想獲取添加位置的父元素並將一些 styles 應用於 typescript 文件中的父元素。 每當將模板添加到 DOM 時,我可以以另一種方式使用生命周期函數之一或 select 父級嗎?
我想到了。 我必須在圖像上添加一個模板標簽,然后使用ViewChildren
類型的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>
Typescript:
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';
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.