6

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.

Kaneki21
  • 1,323
  • 2
  • 4
  • 22
JALLRED
  • 855
  • 1
  • 11
  • 23

2 Answers2

20

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>
Jan B.
  • 6,030
  • 5
  • 32
  • 53
  • Both [hidden]="" and "display:none;" have the same issue - the map code appears to be unable to configure the map. From what I read, the Bing map should be visible when configured and then hidden afterwards. [http://blogs.bing.com/maps/2012/02/23/optimizing-bing-maps-platform-sessions-and-transactions-usage/]. – JALLRED Jul 21 '16 at 20:38
  • 3
    Hmm, I see. 1) The link doesn't seem to work. 2) Your question may be a bit misleading. It is actually not about "ngIf" and "destroying components" but much more about the specific requirements of the Bing map. I'd propose you start a new question making clear the particular issue with Bing. Perhaps you can even provide a plunkr for your case? – Jan B. Jul 21 '16 at 20:49
  • I suppose [hidden] will try to load everything situated in the markup at once. What if I need a bit different scenario: not to load the hidden content until the first time I access it, but once it has been accessed, do not destroy it, only hide? – Alexander Jul 21 '22 at 19:06
2

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