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内容,并输出到控制台中。

相关内容

热门资讯

受玩家影响!wepoker透视... 受玩家影响!wepoker透视脚本苹果版(透视)切实存在有辅助app(有挂教程)-哔哩哔哩1、wep...
据公告内容!sohoo竞技联盟... 据公告内容!sohoo竞技联盟辅助器(透视)好像是真的辅助神器(有挂分享)-哔哩哔哩sohoo竞技联...
透视模拟器!hhpoker透视... 透视模拟器!hhpoker透视方法(透视)一贯真的是有辅助工具(有挂规律)-哔哩哔哩1、hhpoke...
透视模拟器!大菠萝免费辅助器(... 透视模拟器!大菠萝免费辅助器(透视)都是真的有辅助神器(有挂猫腻)-哔哩哔哩1、每一步都需要思考,不...
此事引发网友热议!大菠萝免费辅... 此事引发网友热议!大菠萝免费辅助器(透视)真是是有辅助工具(有挂方法)-哔哩哔哩1、打开软件启动之后...
透视好友!wepoker辅助是... 透视好友!wepoker辅助是真的吗(透视)都是存在有辅助神器(有挂秘籍)-哔哩哔哩1、任何wepo...
连日来!wepoker免费透视... 连日来!wepoker免费透视(透视)好像是真的辅助插件(有挂秘籍)-哔哩哔哩1、点击下载安装,we...
据了解!wepoker透视脚本... 据了解!wepoker透视脚本免费使用视频(透视)一贯真的是有辅助软件(有挂分析)-哔哩哔哩;1、让...
透视实锤!hhpoker德州透... 透视实锤!hhpoker德州透视挂(透视)都是真的有辅助神器(有挂教程)-哔哩哔哩1、hhpoker...
刚刚!wpk有辅助器吗(透视)... 刚刚!wpk有辅助器吗(透视)好像有辅助工具(有挂功能)-哔哩哔哩;1、进入到wpk有辅助器吗是否有...