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.
Angular's ngIf directive does not simply hide and show. It creates and destroys an HTML element based on the result of a JavaScript expression.
Description link. A shorthand form of the directive, *ngIf="condition", is generally used, provided as an attribute of the anchor element for the inserted template. Angular expands this into a more explicit version, in which the anchor element is contained in an <ng-template> element.
When an element gets removed from the page using ngIf, it gets removed completely, its not like the element is hidden using CSS. If you adopt a reactive style for your applications, ngIf is often used in combination with the async pipe, to consume observable data.
When Angular sees the *, the template compiler is going to take the template in its initial form: ... Angular will de-sugar this form of ngIf using the * syntax ...
The * syntax means that ngIf is a structural directive, meaning that it affects the structure of the page. When Angular sees the *, the template compiler is going to take the template in its initial form: ... Angular will de-sugar this form of ngIf using the * syntax ... And Angular is going to de-sugar the *ngIf syntax into the following form: ...
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>
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 wellIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With