Search code examples
angularangular2-directivesngoninit

Directive's onInit method is called many times when the parent element is hidden and shown again


<div *ngIf="variable">
    <directive></directive>
</div>

In the above code snippet (Angular 2), I change the variable from true to false and hence the directive won't render and next when i try to set variable to true again, onInit is called from the directive one more time.

I want the ngOnInit method to be called during the loading of directive for the first time only.

Why my ngOnInit of directive is called everytime when the variable value changes from false ngOnInit true.

Any suggestions.


Solution

  • Instead of use *ngIf use [hidden]="variable".

    When you use *ngIf you're removing the element from the DOM and once you toggle it to true again it'll render the directive again.

    Also, I recommend you to take a look at the hidden docs for possible CSS issues.