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透视有没有(透视)果然真的有辅助app(有挂分享)-哔哩哔哩wepoker透...
随着!wpk真吗(透视)好像是... 随着!wpk真吗(透视)好像是真的辅助修改器(竟然有挂)-哔哩哔哩1、每一步都需要思考,不同水平的挑...
事发当天!wepoker养号规... 事发当天!wepoker养号规律(透视)确实真的有辅助辅助器(真实有挂)-哔哩哔哩一、wepoker...
网友热议!pokemmo手机脚... 网友热议!pokemmo手机脚本(透视)一直有辅助插件(有挂神器)-哔哩哔哩1、完成pokemmo手...
透视挂透视!拱趴大菠萝辅助神器... 透视挂透视!拱趴大菠萝辅助神器(透视)果然真的是有辅助插件(有挂方略)-哔哩哔哩拱趴大菠萝辅助神器辅...
透视ai!wejoker私人辅... 透视ai!wejoker私人辅助软件(透视)切实真的是有辅助安装(新版有挂)-哔哩哔哩1、实时wej...
透视脚本!德州hhpoker是... 透视脚本!德州hhpoker是真的吗(透视)好像有辅助工具(有挂技巧)-哔哩哔哩1、实时德州hhpo...
推出新举措!wepokerpl... 推出新举措!wepokerplus开挂(透视)好像是有辅助神器(确实有挂)-哔哩哔哩wepokerp...
做出回应!we-poker正规... 做出回应!we-poker正规吗(透视)本来存在有辅助修改器(有人有挂)-哔哩哔哩1、进入游戏-大厅...