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

相关内容

热门资讯

透视详细"we-po... 透视详细"we-poker辅助"本来是有辅助插件(哔哩哔哩)1、进入游戏-大厅左侧-新手福利-激活码...
透视开挂"wepok... 透视开挂"wepoker私人局辅助"竟然真的有辅助插件(哔哩哔哩)1、wepoker私人局辅助免费辅...
透视辅助"poker... 透视辅助"pokerrrr2辅助"都是存在有辅助挂(哔哩哔哩)1、上手简单,内置详细流程视频教学,新...
透视透视"大菠萝78... 透视透视"大菠萝789辅助器下载"本来是真的辅助教程(哔哩哔哩)1、大菠萝789辅助器下载模拟器是什...
透视关于"hhpok... 透视关于"hhpoker脚本下载"本来存在有辅助app(哔哩哔哩)1、hhpoker脚本下载脚本辅助...
透视分享"wpk透视... 透视分享"wpk透视是真的吗"其实是真的辅助挂(哔哩哔哩)1、wpk透视是真的吗有没有辅助教程、wp...
透视推荐"hhpok... 透视推荐"hhpoker软件可以玩吗"都是真的有辅助工具(哔哩哔哩)1、进入到hhpoker软件可以...
透视教你"智星菠萝透... 透视教你"智星菠萝透视"好像是真的辅助攻略(哔哩哔哩)1、完成智星菠萝透视辅助器v3.3的残局,帮助...
透视专业"HH平台挂... 透视专业"HH平台挂"原来存在有辅助插件(哔哩哔哩)1、在HH平台挂插件功能辅助器技巧中,中转单元十...
透视曝光"智星德州插... 透视曝光"智星德州插件怎么下载"其实是真的辅助插件(哔哩哔哩)1、透视曝光"智星德州插件怎么下载"其...