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公共底牌,微乐小程序黑科技下载,方针教程(发现有挂)-哔哩哔哩1)wepok...
揭幕透视!wpk作弊,微乐江苏... 揭幕透视!wpk作弊,微乐江苏小程序游戏破解器下载,妙计教程(有挂教学)-哔哩哔哩1、完成wpk作弊...
必备透视!wpk辅助器,微信小... 必备透视!wpk辅助器,微信小程序微乐游戏辅助,大纲教程(有挂教程)-哔哩哔哩1、每一步都需要思考,...
分享透视!wepoker透视脚... 分享透视!wepoker透视脚本安卓,微信微乐辅助ios,要领教程(有挂详情)-哔哩哔哩1、很好的工...
揭露透视!wepoker透视a... 揭露透视!wepoker透视app下载,微乐辅助软件购买平台,法子教程(有挂秘籍)-哔哩哔哩1、起透...
解密透视!hhpoker免费透... 解密透视!hhpoker免费透视脚本,微乐小程序破解版修改器,指南书教程(真的有挂)-哔哩哔哩1、任...
揭露透视!竞技联盟透视插件,微... 揭露透视!竞技联盟透视插件,微乐家乡官方app下载,方式教程(证实有挂)-哔哩哔哩所有人都在同一条线...
有挂透视!wepoker辅助是... 有挂透视!wepoker辅助是真的吗,微乐小程序透视工具,手段教程(有挂教学)-哔哩哔哩1、操作简单...
科普透视!wepoker提高好... 科普透视!wepoker提高好牌率,如何下载微乐自建房黑科技入口,手册教程(有挂细节)-哔哩哔哩1、...
解密透视!德州局透视脚本,微乐... 解密透视!德州局透视脚本,微乐小程序免费黑科技5个玩家常用方法,要领教程(有挂教学)-哔哩哔哩1、下...