4

I'm aware of the difference between *ngIf and hidden property in Angular:

*ngIf: Adds/Removes the element to DOM.

hidden: Simply shows/hides the element in DOM.

What I'm not sure is the proper condition(?) to choose one over the other. Removing an element at one condition and adding it again sounds a bit expensive but at the same time, it doesn't seem right to let it stay in DOM with hidden property.

I've been sticked to *ngIf as much as I can but it sometimes emits an error when I try accessing the element in the *ngIf template even after I change the condition of *ngIf to true (probably because I'm not used to the cycle of the DOM update). In these case, I use hidden property, not because it seems right.

So the point is, I'd like to know the clear standard/criterion to choose one over the other.

Many Thanks.

4 Answers 4

14

I found some better answer in Angular document for your question. Hope it will provide you with clear approach to find out better selection from *ngIf and hidden.

From Angular Guide

The difference between hiding and removing doesn't matter for a simple paragraph. It does matter when the host element is attached to a resource intensive component. Such a component's behavior continues even when hidden. The component stays attached to its DOM element. It keeps listening to events. Angular keeps checking for changes that could affect data bindings. Whatever the component was doing, it keeps doing.

Although invisible, the component—and all of its descendant components—tie up resources. The performance and memory burden can be substantial, responsiveness can degrade, and the user sees nothing.

On the positive side, showing the element again is quick. The component's previous state is preserved and ready to display. The component doesn't re-initialize—an operation that could be expensive. So hiding and showing is sometimes the right thing to do.

But in the absence of a compelling reason to keep them around, your preference should be to remove DOM elements that the user can't see and recover the unused resources with a structural directive like NgIf .

These same considerations apply to every structural directive, whether built-in or custom. Before applying a structural directive, you might want to pause for a moment to consider the consequences of adding and removing elements and of creating and destroying components.

7
  • Wow I hadn't thought of it this way! It helped me a lot. Thanks! Jul 13, 2018 at 4:49
  • @DongBin Kim glad to help you! happy coding :)
    – coder
    Jul 13, 2018 at 4:53
  • 3
    sidenote: if you use *ngIf the page can flicker due to removing the element from DOM whereas [hidden] will not affect the design and position of elements of DOM.
    – xkeshav
    Jul 13, 2018 at 5:02
  • 1
    @coder Apart from the resource/memory point of view, what about the issue I described in my writing? Maybe because of the DOM creation timing issue, I sometimes can't access the element via template variable with the error Cannot read property 'nativeElement' of undefined. In these cases, I always had to choose hidden property. Jul 13, 2018 at 5:07
  • @DongBin Kim yes your thought is correct. as soon as we change the *ngIf to true and then we are try access the element at the same time we could have such glitches. have to wait until they are ready to use
    – coder
    Jul 13, 2018 at 5:17
4

There have been two occasions in which I have had reasons to choose one over the other:

  • Choose *ngIf when using [hidden] will cause a performance problem (hundreds of hidden tags are still in the DOM and can cause sluggish rendering of your website).
  • Choose [hidden] when you still need to initialize the hidden component, and pass events to it, even if you are not going to show it.

Besides these 2 rules, it's a matter of what feels right to your setup.

I give you an example of each one I had found in real life:

Choose *ngIf when using [hidden] will cause a performance problem

Imagine you have a Ticket object and you keep track of modification to each ticket by using a list of Log objects. Each log represents a type of change that needs to be rendered differently (for example: closing a ticket generates a log that shows the old and new state, but adding a file to a ticket shows a preview of the file).

One possible implementation is using [hidden] like this:

<span [hidden]="logType !== 1">...</span>
<span [hidden]="logType !== 2">...</span>
<span [hidden]="logType !== 3">...</span>
...
<span [hidden]="logType !== 30">...</span>

Then for every log in your page you'll have 29 hidden DOM elements. Now, if your ticket gets modified a lot, say 10 modifications you'll end up with 290 hidden elements in your DOM, which will be using memory and are slower to render.

In that case, changing the [hidden] to *ngIf removes completely the 290 extra objects.

Choose [hidden] when you still need to initialize the hidden component

Check this other situation:

Ticket.html

<ng-container *ngIf="numLogs > 0">
    <h1>Logs</h1>
    <ticket-logs [ticketId]="ticket.id"
                 (onNumLogsRetrieved)="setNumLogs($event)"></ticket-logs>
</ng-container>

Where setNumLogs($event) is the one that sets the value of numLogs.

Notice that with a *ngIf the ticket-logs component will never be instantiated, so numLogs will always be 0. In this case you need to use a [hidden] which gives the ticket-logs component the opportunity to invoke setNumLogs to hide the h1 and itself.

(Note in this case we can't have ticket-logs hide its own contents because we would still be showing the h1 tag.)

3
  • Thanks for your detailed explanation. Let me ask you one thing to make something clear: Say, there's a code like <ng-container *ngIf="show"><div #div></div></ng-container>. At certain point, I want to access the div element so I try like: this.show = true; // do Something with this.div.nativeElement And the problem is that an error is emitted saying Cannot read property 'nativeElement' of undefined. Is this an expected behaviour? I'm asking this because in my knowledge, I should be able to access it because I set the show variable to true. Jul 13, 2018 at 5:20
  • That can certainly give you trouble because of the #div: if you reference #div while Angular thinks show = false then #div won't exist. Notice that setting this.show = true doesn't immediately cause the #div to exist, you'll need to wait until Angular has digested the changes and updated the DOM, and then you will have access to #div. If you could provide the exact code (in a different question as this one is partly unrelated) then we could see how the code could be refactored for not needing to wait until Angular has updated the DOM.
    – DWilches
    Jul 13, 2018 at 5:28
  • stackoverflow.com/questions/51318338/… I've posted a question about this matter. I'd appreciate your insight if you would take a look! Jul 13, 2018 at 5:45
1

ngIf is a directive provided by the Angular. It is used to add or remove the html content in angular applications. If we are providing false it will remove the content.

eg

<div *ngIf="isValid"> Data is valid. </div> 

hidden can be user to just hide the content from page. It doesn't remove the DOM elements. But it just hide

eg

<div hidden> Data is valid. </div> 

When should we use *ngIf?

It can be used when some fields in a form which should be removed for a particular user. Then you can use *ngIf. Because anyone can make the DOM element visible by removing the hidden from dom. So if a field should not be used by anyone in a particular condition it is better to user *ngIf

0

*ngIf is used when you want the DOM element to be dynamically inserted based on a condition. With the hidden attribute, you will always have the DOM element present and you can get it anytime from the DOM, but it won't be visible(obviously) to the user.

So, use *ngIf when you don't want the element to be present in the DOM at all. Use hidden element when you want to have some data stored(for posting purpose perhaps, with the visible form elements) and need to access it for some reason, keeping it hidden for the user.

1
  • Sometimes, I wanted certain elements to be removed completely and dynamically inserted in DOM so I tried it with *ngIf but as I described in my writing, because of the cycle/timing issue, I couldn't access the element in the *ngIf directive with template variables even after changing the condition to true so I just chose hidden property instead. Jul 13, 2018 at 4:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.