2
我一直在玩A2一段时间,并且我明白我的问题是由于在A2中和由于html中的*ngIf
而一切初始化和运行的顺序造成的,我不明白的是为什么或如何得到我想要的结果。无法通过ngIf中的ID获取元素
使用下面的测试组件:
@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
中的console.log
test1
回报null
其中作为test2
回报元件。我知道那是因为它内部的*ngIf
,但我不明白为什么或怎样做才能访问该元素的一次呈现,所以我可以为谷歌地图API
编辑一些更新的一部分,与它互动我愚蠢地排除的代码。
即使在'ngAfterViewInit'中,仍然返回NULL。尽可能多的使用代码,我可以告诉它,因为api调用的异步(当我愚蠢地排除它时,我将更新我的答案)。如果我删除异步调用,然后'ngAfterViewInit()'工作,如果我保留'订阅',那么它不。 – Doug