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

前端 未结 1 1093
你的背包
你的背包 2020-12-01 13:19

I\'m encountering a simple problem which has a hacky solution of setTimeout(...,0).

Looking at this simple code :

@Component({         


        
相关标签:
1条回答
  • 2020-12-01 14:11

    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

    0 讨论(0)
提交回复
热议问题