Angular9中如何在使用ng-container和ngIf添加元素后获取父节点?
创始人
2024-10-22 17:00:59
0

在Angular 9中,如果你想在使用ng-container和ngIf添加元素后获取父节点,你可以使用ViewChild装饰器来获取父节点的引用。以下是一个解决方法的代码示例:

在父组件的HTML模板中,使用ng-container和ngIf来添加元素:

Child Element

在父组件的 TypeScript 文件中,使用ViewChild装饰器来获取父节点的引用:

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {

  @ViewChild('parentContainer', {static: false}) parentContainer: ElementRef;

  showChildElement = true;

  ngAfterViewInit() {
    console.log(this.parentContainer.nativeElement); // 输出父节点的引用
  }
}

在上述代码中,我们使用ViewChild装饰器获取了父节点的引用,并在ngAfterViewInit生命周期钩子中打印了父节点的引用。请确保将ViewChild装饰器应用在父组件的类成员变量上,并使用{static: false}选项来指定在视图初始化后获取父节点的引用。

当showChildElement为true时,ng-container中的子元素会被添加到父节点中。在ngAfterViewInit中,你可以通过this.parentContainer.nativeElement来访问父节点的引用,并进行进一步的操作。

希望这个解决方法对你有所帮助!

相关内容

热门资讯

透视神器!hhpoker辅助挂... 透视神器!hhpoker辅助挂(透视)hhpoker到底可以作必弊码(原来一直总是有挂)-哔哩哔哩1...
透视神器!模拟器打开hhpok... 透视神器!模拟器打开hhpoker(透视)hhpoker免费透视脚本(切实有透视)-哔哩哔哩1、首先...
透视攻略!hh poker软件... 透视攻略!hh poker软件(透视)hhpoker德州机器人(原来一直总是有透视)-哔哩哔哩1、很...
透视软件!潮汕激k辅助(辅助)... 透视软件!潮汕激k辅助(辅助)新九五辅助微信脚本(其实存在有挂)-哔哩哔哩一、新九五辅助微信脚本可以...
透视脚本!aapoker脚本怎... 透视脚本!aapoker脚本怎么用(透视)aapoker怎么拿好牌(一贯一直都是有透视)-哔哩哔哩1...
透视攻略!hhpoker到底可... 透视攻略!hhpoker到底可以作必弊码(透视)德扑HHpoker有挂吗(一贯一直总是有辅助器)-哔...
透视app!德州透视插件(透视... 透视app!德州透视插件(透视)hhpoker辅助器(真是有透视)-哔哩哔哩1、在德州透视插件插件功...
透视攻略!拱趴大菠萝有挂吗(透... 透视攻略!拱趴大菠萝有挂吗(透视)pokemmo手机版透视脚本(总是是有辅助器)-哔哩哔哩1、不需要...
透视脚本!欢聚水鱼脚本(辅助)... 您好,jj斗地主捕鱼辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多...
透视软件!hhpoker作必弊... 透视软件!hhpoker作必弊实战视频(透视)hhpoker透视脚本下载(其实存在有脚本)-哔哩哔哩...