Angular2选择一个带有ngIf的元素

Sci*_*ion 2 angular

这是我的HTML:

<div id="foo" (mouseover)="blah()" *ngIf="isDisplayed"></div>
Run Code Online (Sandbox Code Playgroud)

我的js:

isDisplayed: boolean = false
blah() {
  this.isDisplayed = true
  console.log(document.getElementById('foo'))
}
Run Code Online (Sandbox Code Playgroud)

但是,我的console.log确实打印为null.如果我添加一个setTimeout围绕console.log,它的工作原理但这是哈克,并会在几个事件将是比赛中的一个烂摊子.我的意思是,我确实getElementById在模板ngIf更新之前运行了.我怎么能确定模板在运行时更新了console.log

Gün*_*uer 5

显式调用更改检测,然后Angular将立即更新DOM.

constructor(private cdRef:ChangeDetectorRef) {}

isDisplayed: boolean = false
blah() {
  this.isDisplayed = true;
  this.cdRef.detectChanges();
  console.log(document.getElementById('foo'));
}
Run Code Online (Sandbox Code Playgroud)