How to check whether ngIf has taken effect

前端 未结 2 1686
深忆病人
深忆病人 2020-12-06 04:27

What I\'m Doing
I have a component that hides/shows using *ngIf based on a simple Boolean. When the component becomes visible I want to app

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 05:24

    This question is fairly old, and the current solution may not have been available at that time.

    The setTimeout() method is perfectly viable, but has a significant downside. If you just set a class to position an element, like I did, you get a jumpy result, since the code is executed after the angular loop.

    Using ChangeDetectorRef produces a result that does not jump.

    So instead of this:

    class Foo {
      public isDisplayed = false;
    
      constructor(@Inject(ElementRef) private elementRef: ElementRef) {
      }
    
      public someMethod(): void {
         this.isDisplayed = true;
         setTimeout(() => {
             const child = this.elementRef.nativeElement.querySelector('.child-element');
             // ...
         });
      }
    }
    

    You could do this:

    class Foo {
      public isDisplayed = false;
    
      constructor(@Inject(ElementRef) private elementRef: ElementRef,
                  @Inject(ChangeDetectorRef) private changeDetectorRef: ChangeDetectorRef) {
      }
    
      public someMethod(): void {
         this.isDisplayed = true;
         this.changeDetectorRef.detectChanges();
         const child = this.elementRef.nativeElement.querySelector('.child-element');
         // ...
      }
    }
    

提交回复
热议问题