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有透视功能吗(透视)其实真的有挂(有挂秘诀开挂辅助软件)-哔哩哔哩1、完成hh...
长期以来!poker红龙辅助,... 长期以来!poker红龙辅助,pokemmo脚本辅助,烘培教程(有挂方略)-哔哩哔哩1、上手简单,内...
近日!pokemmo辅助器手机... 近日!pokemmo辅助器手机版下载(透视)其实是有挂的(的确有挂开挂辅助软件)-哔哩哔哩1、pok...
围绕透视问题!wepoker私... 围绕透视问题!wepoker私局代打,hhpoker真的假的,方式教程(存在有挂)-哔哩哔哩1、围绕...
这一问题亟待解决!wpk控制牌... 这一问题亟待解决!wpk控制牌是真的吗(透视)果然是有挂的(有挂讲解开挂辅助下载)-哔哩哔哩1、wp...
日前!wepoker可以透视码... 日前!wepoker可以透视码,佛手在线大菠萝技巧,方式教程(有挂助手)-哔哩哔哩1、完成佛手在线大...
现就发布提示!wejoker免... 现就发布提示!wejoker免费脚本(透视)一直确实有挂(有挂透明挂开挂辅助下载)-哔哩哔哩一、we...
现场直击!wepoker私人局... 现场直击!wepoker私人局透视插件,xpoker透视辅助,技法教程(有挂教程)-哔哩哔哩1、在w...
于此同时!hhpoker辅助码... 于此同时!hhpoker辅助码怎么用(透视)果然真的有挂(有挂方略开挂辅助平台)-哔哩哔哩1、在hh...
备受关注的!wepoker买钻... 备受关注的!wepoker买钻石有用吗,wepoker一直输的号能继续打吗,要领教程(有挂秘诀)-哔...