Angular 4 – What is the right way to “wait for operation”?

1) You can force Angular to update the DOM by calling cdRef.detectChanges

constructor(private cdRef: ChangeDetectorRef) {}

analyzeDom(){
  this.cdRef.detectChanges();
  alert($("div .mySpan").length)

Plunker

As setTimeout is macrotask therefore it is running next digest cycle.
It means that after calling setTimeout all components tree will be checked

cdRef.detectChanges doesn’t call appRef.tick(). It only executes change detection component itself and its children.

2) or you can wait until Angulat has updated DOM by subscribing to zone.onMicrotaskEmpty

import 'rxjs/add/operator/first';

constructor(private zone: NgZone) {}
...
this.zone.onMicrotaskEmpty.first().subscribe(() => this.analyzeDom());

Note: first operator can cause memory leak. See https://github.com/angular/material2/issues/6905

Subscribing to onMicrotaskEmpty doesn’t call change detection cycle

Plunker

Leave a Comment