JALLRED
JALLRED

Reputation: 955

Angular2: ngIf without destroying component

I have a web page with a tab control taking up a portion of the screen. The tabs are shown/hidden using *ngIf and comparing the selected tab against an enum. Thus the components are destroyed / created every time the user changes tabs.

Usually this is fine, but one of the tabs contains a Bing map. Every time the tab is selected the map control is reloaded - causing the map to briefly display the current IP location until the desired location and pins are loaded (a fraction of a second later).

The only way I was able to get around this was to stop using *ngIf for that tab and instead set a custom style:

.hide { height: 0px; overflow: hidden; }

So far this appears to work great, but I am concerned that this will give rise to bugs down the road.

Is there an angular2 blessed way to hide a component without destroying the component?

Thanks.

Upvotes: 7

Views: 14028

Answers (2)

Sarthak Maheshwari
Sarthak Maheshwari

Reputation: 537

use [hidden] property of angular which does not remove the section/ component from the DOM instead hides it from the view thus there is no need of reinstantiating the component in the DOM (similar to css display: hidden property)

  • [hidden]= true -> Hides the Section from the view but it exists in DOM
  • [hidden]= false -> Show's the section in view
  • *ngIf="false" -> Hides the Section from the view & Removes it from the DOM as well

Upvotes: 3

Jan B.
Jan B.

Reputation: 6458

The [hidden] property is what you are looking for. It more or less replaced ng-show / ng-hide in Angular2.

Find it in the offical docs or see their code sample here:

<h3 [hidden]="!favoriteHero">
   Your favorite hero is: {{favoriteHero}}
</h3>

Upvotes: 22

Related Questions