ngIf and ngSwitch AngularJS

36,420

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.

Share:
36,420
Harry
Author by

Harry

Updated on July 25, 2020

Comments

  • Harry
    Harry almost 4 years

    What's practical difference between ngIf and ngSwitch? Both directives manipulate the DOM, but ngSwitch is more verbose. Is the typical case to just use ngIf unless you need something really big in which case use ngSwitch?

    Is there a situation where ngSwitch and ngIf are not direct replacements? Or is their only practical difference the syntax?

  • poshest
    poshest about 7 years
    This is a useful comment, but in no way answers the actual question.
  • Joe Hansen
    Joe Hansen about 3 years
    For instance, ngSwitch is better if you have a few cases and a default case that is essentially != any of the above