angular – 无法在ngIf内按ID获取元素
发布时间:2020-12-17 17:28:04 所属栏目:安全 来源:网络整理
导读:我已经玩了A2一段时间了,我明白我的问题是由于所有内容初始化并在A2中运行的顺序,并且由于html中的* ngIf,但我不明白的是为什么或如何得到我想要的结果. 使用以下测试组件: @Component({ moduleId: module.id,selector: 'test',templateUrl: 'test.componen
我已经玩了A2一段时间了,我明白我的问题是由于所有内容初始化并在A2中运行的顺序,并且由于html中的* ngIf,但我不明白的是为什么或如何得到我想要的结果.
使用以下测试组件: @Component({ moduleId: module.id,selector: 'test',templateUrl: 'test.component.html' }) export class TestComponent implements OnInit { test: any; settest():void{ //this.test = {test: 1}; --This works using ngAfterViewInit //This causes the console.log in ngAfterViewInit to be null this.route.params .switchMap((params: Params) => this.testService.getTest(params['id'])) .subscribe(test => { this.test = test; }); } ngOnInit(): void { this.settest(); console.log(document.getElementById('test1')); --Null console.log(document.getElementById('test2')); -- Not NUll } ngAfterViewInit(): void { console.log(document.getElementById('test1')); --Null console.log(document.getElementById('test2')); -- Not NUll } } 和test.component.html <div *ngIf="test"> <div id="test1"></div> </div> <div id="test2"></div> 我不明白为什么,即使在ngOnInit中,test1的console.log返回null,因为test2返回元素.我知道这是因为它在* ngIf中,但我不明白为什么或一旦它被渲染后访问该元素该怎么做所以我可以作为谷歌地图API的一部分与它进行交互 编辑更新了一些我愚蠢地排除的代码. 解决方法
如果在该元素上使用任何角度上下文,则可以在ngAfterViewInit生命周期钩子中引用DOM元素.您可以期望DOM元素(具有Angular上下文)在ngAfterViewInit生命周期钩子中完全可用.
ngOnInit(): void { this.settest(); console.log(document.getElementById('test1')); // not rendered console.log(document.getElementById('test2')); } ngAfterViewInit(){ console.log(document.getElementById('test1')); // rendered } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |