Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: conditional display, bind to [hidden] property vs. *ngIf directive [duplicate]

Tags:

html

angular

In Angular2, let's say I want to conditionally display a <div> block. What's the difference between the following two ways.

  1. <div [hidden]=isLoaded>Hello World!</div> where isLoaded is a boolean in corresponding .ts file.

  2. <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?

like image 346
Bing Lu Avatar asked Sep 29 '16 18:09

Bing Lu


People also ask

What is the difference between ngIf and hidden?

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.

What is hidden property in Angular 2?

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.

How can I hide and show a div with using * ngIf in angular?

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.

Does ngIf remove element from DOM?

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.


1 Answers

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.

like image 178
Husein Roncevic Avatar answered Sep 23 '22 05:09

Husein Roncevic