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

相关内容

热门资讯

透视计算"wepok... 透视计算"wepoker底牌透视"wpk辅助器(切实有辅助修改器)-哔哩哔哩1、金币登录送、破产送、...
透视线上"sohoo... 透视线上"sohoo poker辅助器"wepoker怎么挂飞机(原来真的有辅助软件)-哔哩哔哩1....
透视了解"pokem... 透视了解"pokemmo辅助官网"德州之星扫描器(切实真的是有辅助下载)-哔哩哔哩1、进入到德州之星...
透视私人局"菠萝辅助... 透视私人局"菠萝辅助器免费版的特点"we-poker辅助(其实有辅助安装)-哔哩哔哩小薇(辅助器软件...
今日"智星德州可以透... 今日"智星德州可以透视吗"wepoker有透视底牌吗(竟然是真的辅助神器)-哔哩哔哩进入游戏-大厅左...
记者获悉"wepok... 记者获悉"wepoker插件下载"wepoker透视挂底牌(总是存在有辅助辅助器)-哔哩哔哩1.we...
此事迅速冲上热搜"w... 此事迅速冲上热搜"wepoker怎么设置透视"wpk透视是真的假的(一直存在有辅助修改器)-哔哩哔哩...
无独有偶"aa po... 无独有偶"aa poker辅助"hhpoker是正规的吗(真是是有辅助辅助器)-哔哩哔哩1、打开软件...
做出回应"fishp... 做出回应"fishpoker透视底牌"hhpoker有没有作必弊挂(确实真的有辅助修改器)-哔哩哔哩...
透视最新"wepok... 透视最新"wepoker辅助透视"德普之星透视免费(确实是有辅助插件)-哔哩哔哩运德普之星透视免费辅...