ngIf and ngSwitch AngularJS
Solution 1
Michele Tilley's got it exactly right, I believe, particularly in pointing out the contrast with ngShow
/ngHide
. There's one additional difference to note: ng-If
will detach and re-attach an element in-place. But ng-Switch
has an outer containing element on which you declare the main directive and its condition: ng-switch="expression"
. The conditional content within that outer element will be append()
-ed as the last child of the outer element, thus changing its position relative to any non-conditional content within the outer element.
And, see this CodePen for an interactive demo of all three, showing the differences in execution.
EDIT: This behavior changed in Angular 1.2. Elements are now left in place. The Codepen above mentions and demonstrates this, providing a link to a 1.08 Plunk that has sadly been wiped out...
Solution 2
ngIf
is basically a version of ngSwitch
with a single condition. It's different from ngShow
in that it removes the actual DOM element rather than simply hiding it. If you're using an ngSwitch
with just a singly truthy condition check, then I believe ngIf
will do the same thing.
Solution 3
One more difference would be that ngIf and ngSwitch create new scopes, while ngShow/ngHide don't.
Solution 4
You can think in ngIf/ngSwitch in the same way you do with if/switch when you are coding. Obviously they do almost the same thing, but there are cases that a ngIf is better and there are cases where nfSwitch is better.
Harry
Updated on July 25, 2020Comments
-
Harry almost 4 years
What's practical difference between
ngIf
andngSwitch
? Both directives manipulate the DOM, butngSwitch
is more verbose. Is the typical case to just usengIf
unless you need something really big in which case usengSwitch
?Is there a situation where
ngSwitch
andngIf
are not direct replacements? Or is their only practical difference the syntax? -
poshest about 7 yearsThis is a useful comment, but in no way answers the actual question.
-
Joe Hansen about 3 yearsFor instance,
ngSwitch
is better if you have a few cases and a default case that is essentially!= any of the above