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.)