In Angular2, let's say I want to conditionally display a <div>
block. What's the difference between the following two ways.
<div [hidden]=isLoaded>Hello World!</div>
where isLoaded
is a boolean in corresponding .ts
file.
<div *ngIf=isLoaded>Hello World!</div>
I do know that even if the <div>
is not shown in the page, 1. still has the <div>
in the DOM while 2. doesn't. Are there any other differences? What're the pros and cons of each of them?
ngIf will comment out the data if the expression is false. This way the data are not even loaded, causing HTML to load faster. [hidden] will load the data and mark them with the hidden HTML attribute. This way data are loaded even if they are not visible.
Angular 2 [hidden] is a special case binding to hidden property. It is closest cousin of ng-show and ng-hide. It is more powerful to bind any property of elements. Both the ng-show and ng-hide are used to manage the visibility of elements using ng-hide css class.
Copy # Angular element = false; We will use *ngIf to display and hide our div based on the condition. As you can see in the above example, we have set a condition if the element is true , the div will be displayed, and if the condition is false , it will not display.
The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
The difference is that *ngIf
will remove the element from the DOM, while [hidden]
actually plays with the CSS style by setting display:none
. However, the problem with [hidden]
is that it can be overiden so the div
, as in your case, would be displayed and you would be scratching your head why it doesn't work.
To sum things up, *ngIf
and [hidden]
are not the same at all. The former removes an element from DOM, while the latter toggles display
CSS property.
If 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