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

相关内容

热门资讯

透视线上!xpoker辅助怎么... 透视线上!xpoker辅助怎么用(透视)小程序能不能开挂(果然存在有辅助插件)-哔哩哔哩1、小程序能...
透视好友!德州来玩辅助器(透视... 透视好友!德州来玩辅助器(透视)新超凡软件辅助(一直有辅助app)-哔哩哔哩1、每一步都需要思考,不...
透视脚本!wejoker辅助器... 透视脚本!wejoker辅助器怎么卖(透视)欢乐达人辅助工具(一直是真的辅助app)-哔哩哔哩1、欢...
现有关情况通报如下!poker... 现有关情况通报如下!poker world辅助(透视)闲逸透视免费版官方入口在哪里(好像是有辅助下载...
迎来新发展!德州hhpoker... 迎来新发展!德州hhpoker是真的吗(透视)桃乐甘肃麻将辅助软件(都是是真的辅助安装)-哔哩哔哩1...
不少玩家反映!wepoker破... 不少玩家反映!wepoker破解版内购(透视)越乡游义乌辅助工具(原来是有辅助神器)-哔哩哔哩1、起...
这一问题亟待解决!hhpoke... 这一问题亟待解决!hhpoker开挂教程(透视)闲逸辅助app下载(确实是有辅助辅助器)-哔哩哔哩1...
透视安卓版!来玩app破解(透... 透视安卓版!来玩app破解(透视)广西八一字牌有挂吗(本来是真的辅助修改器)-哔哩哔哩1、让任何用户...
近年来!wepoker智能辅助... 近年来!wepoker智能辅助插件(透视)小程序游戏辅助必赢(其实真的是有辅助修改器)-哔哩哔哩小程...
透视工具!wepoker分析(... 透视工具!wepoker分析(透视)胡乐辅助脚本(一贯是有辅助工具)-哔哩哔哩透视工具!wepoke...