【发布时间】:2017-02-07 07:16:40
【问题描述】:
我玩 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 的一部分与之交互
编辑更新了一些我愚蠢地排除的代码。
【问题讨论】:
标签: angular getelementbyid angular-ng-if