Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngIf and ngSwitch AngularJS

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?

like image 701
Harry Avatar asked May 24 '13 19:05

Harry


People also ask

What is the difference between ngIf and ngSwitch?

For *ngIf , every condition will be checked and the code inside the true condition will be executed. For [ngSwitch] , only the code inside the specific case will be executed (using break; ). So, [ngSwitch] will be faster where there are multiple cases.

Can I use ngIf and ngSwitch together?

With NgIf we can conditionally add or remove an element from the DOM . If we are faced with multiple conditions a cleaner alternative to multiple nested NgIf statements is the NgSwitch series of directives.

What is ngSwitch in angular?

AngularJS ng-switch Directive The ng-switch directive lets you hide/show HTML elements depending on an expression. Child elements with the ng-switch-when directive will be displayed if it gets a match, otherwise the element, and its children will be removed.

Can we use ngIf and Ng show together?

ng-if is better in this regard. Using it in place of ng-show will prevent the heavy content from being rendered in the first place if the expression is false. However, its strength is also its weakness, because if the user hides the chart and then shows it again, the content is rendered from scratch each time.


2 Answers

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.

like image 116
Michelle Tilley Avatar answered Sep 18 '22 11:09

Michelle Tilley


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

like image 29
XML Avatar answered Sep 20 '22 11:09

XML