AngularViewChild与ng-template一起使用时无法获取所有的innerHTML。
创始人
2024-10-29 22:00:39
0

在使用ViewChild获取ng-template内容时,由于ng-template不直接渲染内容,所以ViewChild只能获取到ng-template本身,而无法获取到它内部的HTML内容。解决方法是使用ng-container包裹ng-template,并在ngAfterViewInit生命周期钩子中获取ng-container的innerHTML。 示例如下:

HTML:

Hello World!

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

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

@ViewChild('myContainer', {static: true}) myContainer: ElementRef;

ngAfterViewInit() { console.log(this.myContainer.nativeElement.innerHTML); }

}

在上述代码示例中,使用ng-container包裹ng-template,并将#myContainer指向ng-container,在ngAfterViewInit生命周期钩子中使用ViewChild获取#myContainer元素,并使用nativeElement属性获取innerHTML。此时可以获得ng-template内部的HTML内容,并输出到控制台中。

相关内容

热门资讯

透视真的!德州局hhpoker... 透视真的!德州局hhpoker(透视)丽水茶苑辅助下载app(原来是有辅助下载)-哔哩哔哩1、游戏颠...
透视苹果版!hhpoker是真... 透视苹果版!hhpoker是真的假的(透视)微信小程序多乐游戏辅助脚本(本来存在有辅助平台)-哔哩哔...
透视软件!aapoker透视脚... 透视软件!aapoker透视脚本入口(透视)超级三加一辅助(一直是真的辅助工具)-哔哩哔哩进入游戏-...
透视辅助!hhpoker德州有... 透视辅助!hhpoker德州有挂吗(透视)免费随意玩辅助器(切实存在有辅助插件)-哔哩哔哩1、操作简...
透视免费!aapoker俱乐部... 透视免费!aapoker俱乐部靠谱吗(透视)全民比鸡脚本(其实有辅助安装)-哔哩哔哩一、全民比鸡脚本...
来临!hhpoker有透视功能... 来临!hhpoker有透视功能吗(透视)新金龙辅助(本来存在有辅助工具)-哔哩哔哩1、很好的工具软件...
透视代打!红龙poker辅助平... 透视代打!红龙poker辅助平台(透视)四海茶馆游戏辅助(都是是有辅助下载)-哔哩哔哩1.四海茶馆游...
透视玄学!pokemomo辅助... 透视玄学!pokemomo辅助软件(透视)开心十三张透视(总是有辅助平台)-哔哩哔哩;1、开心十三张...
透视app!wepoker俱乐... 您好,透视辅助器免费欢聚水鱼这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】...
此事备受玩家关注!wpk私人局... 此事备受玩家关注!wpk私人局辅助是真的吗(透视)来来拼十辅助(好像是真的辅助插件)-哔哩哔哩1、点...