Angularjs - When To Favor Ng-if Vs. Ng-show/ng-hide? - Stack Overflow

    1. Home
    2. Questions
    3. Tags
    4. Users
    5. Companies
    6. Labs
    7. Jobs
    8. Discussions
    9. Collectives
    10. Communities for your favorite technologies. Explore all Collectives

  1. Teams

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

    Try Teams for free Explore Teams
  2. Teams
  3. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Get early access and see previews of new features.

Learn more about Labs When to favor ng-if vs. ng-show/ng-hide? Ask Question Asked 10 years, 10 months ago Modified 6 days ago Viewed 235k times 540

I understand that ng-show and ng-hide affect the class set on an element and that ng-if controls whether an element is rendered as part of the DOM.

Are there guidelines on choosing ng-if over ng-show/ng-hide or vice-versa?

Share Improve this question Follow edited Nov 5, 2022 at 21:37 XML's user avatar XML 19.5k9 gold badges65 silver badges66 bronze badges asked Feb 19, 2014 at 1:42 Patrice Chalin's user avatar Patrice ChalinPatrice Chalin 16.1k7 gold badges35 silver badges44 bronze badges 2
  • 6 possible duplicate of what is the difference between ng-if and ng-show/ng-hide – Gajus Commented Oct 6, 2014 at 14:22
  • 1 Not related to dart language. – naXa stands with Ukraine Commented Sep 21, 2015 at 10:13
Add a comment |

7 Answers 7

Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 728

Depends on your use case but to summarise the difference:

  1. ng-if will remove elements from DOM. This means that all your handlers or anything else attached to those elements will be lost. For example, if you bound a click handler to one of child elements, when ng-if evaluates to false, that element will be removed from DOM and your click handler will not work any more, even after ng-if later evaluates to true and displays the element. You will need to reattach the handler.
  2. ng-show/ng-hide does not remove the elements from DOM. It uses CSS styles to hide/show elements (note: you might need to add your own classes). This way your handlers that were attached to children will not be lost.
  3. ng-if creates a child scope while ng-show/ng-hide does not

Elements that are not in the DOM have less performance impact and your web app might appear to be faster when using ng-if compared to ng-show/ng-hide. In my experience, the difference is negligible. Animations are possible when using both ng-show/ng-hide and ng-if, with examples for both in the Angular documentation.

Ultimately, the question you need to answer is whether you can remove element from DOM or not?

Share Improve this answer Follow edited Jan 31, 2018 at 3:00 Nhan's user avatar Nhan 3,8756 gold badges34 silver badges40 bronze badges answered Feb 19, 2014 at 2:58 markovuksanovic's user avatar markovuksanovicmarkovuksanovic 15.9k14 gold badges50 silver badges57 bronze badges 16
  • 19 You can use CSS3 animations with ng-if. Check the Animations paragraph and the example in the docs. Also with ng-hide/ng-show the css selectors like :first-child or :nth-child won't work properly since the hidden elements will be also counted. – Łukasz Wojciechowski Commented Mar 17, 2014 at 8:38
  • 4 Animation service in angular.dart is relatively new. At the time of writing this it wasn't available. – markovuksanovic Commented Mar 17, 2014 at 22:23
  • 47 You first point is a non-issue if you're using directives (like ng-click) to bind handlers , as you should be. – Kevin C. Commented Jun 18, 2014 at 19:18
  • 9 Also, ng-if creates a new scope while ng-show doesn't. – martin Commented Oct 8, 2014 at 17:17
  • 9 It should also be mentioned that adding and removing elements from the DOM can incur a high performance cost if done frequently. – Kevin C. Commented Nov 12, 2014 at 1:29
| Show 11 more comments 130

See here for a CodePen that demonstrates the difference in how ng-if/ng-show work, DOM-wise.

@markovuksanovic has answered the question well. But I'd come at it from another perspective: I'd always use ng-if and get those elements out of DOM, unless:

  1. you for some reason need the data-bindings and $watch-es on your elements to remain active while they're invisible. Forms might be a good case for this, if you want to be able to check validity on inputs that aren't currently visible, in order to determine whether the whole form is valid.
  2. You're using some really elaborate stateful logic with conditional event handlers, as mentioned above. That said, if you find yourself manually attaching and detaching handlers, such that you're losing important state when you use ng-if, ask yourself whether that state would be better represented in a data model, and the handlers applied conditionally by directives whenever the element is rendered. Put another way, the presence/absence of handlers is a form of state data. Get that data out of the DOM, and into a model. The presence/absence of the handlers should be determined by the data, and thus easy to recreate.

Angular is written really well. It's fast, considering what it does. But what it does is a whole bunch of magic that makes hard things (like 2-way data-binding) look trivially easy. Making all those things look easy entails some performance overhead. You might be shocked to realize how many hundreds or thousands of times a setter function gets evaluated during the $digest cycle on a hunk of DOM that nobody's even looking at. And then you realize you've got dozens or hundreds of invisible elements all doing the same thing...

Desktops may indeed be powerful enough to render most JS execution-speed issues moot. But if you're developing for mobile, using ng-if whenever humanly possible should be a no-brainer. JS speed still matters on mobile processors. Using ng-if is a very easy way to get potentially-significant optimization at very, very low cost.

Share Improve this answer Follow edited May 6, 2014 at 21:51 answered May 6, 2014 at 21:43 XML's user avatar XMLXML 19.5k9 gold badges65 silver badges66 bronze badges 2
  • 6 Very nice addition to the above answer. Given with some good context, which also helps the decision making. Thanks. – Sean Commented Jul 31, 2014 at 12:36
  • 1 ng-show can be useful when you have, say tabs each with a lot of content that takes time to render. After the first rendering, moving between tabs will be instant, whereas ng-if would require re-rendering, binding events etc. The downside as you say, is that creates watches executing in the background. Angular desperately needs ng-ifshowwatch – poshest Commented Sep 3, 2016 at 12:03
Add a comment | 53

From my experience:

1) If your page has a toggle that uses ng-if/ng-show to show/hide something, ng-if causes more of a browser delay (slower). For example: if you have a button used to toggle between two views, ng-show seems to be faster.

2) ng-if will create/destroy scope when it evaluates to true/false. If you have a controller attached to the ng-if, that controller code will get executed every time the ng-if evaluates to true. If you are using ng-show, the controller code only gets executed once. So if you have a button that toggles between multiple views, using ng-if and ng-show would make a huge difference in how you write your controller code.

Share Improve this answer Follow answered Oct 7, 2014 at 23:08 Yi Z's user avatar Yi ZYi Z 9811 gold badge10 silver badges13 bronze badges 4
  • 5 That's a huge true! ng-if does not necessarily make your frontend faster. It depends on your needs. Actually it could make the other way around if you are using in the wrong situation. – Thiago C. S Ventura Commented Oct 14, 2015 at 13:52
  • 1 But according to me as ng-if does't render onto DOM so it is fast as compared to ng-show/hide. am i wrong pls let me correct at that point. – Pardeep Jain Commented Nov 21, 2015 at 7:38
  • 1 ng-if would be faster if it evaluates to false, since, as you say, nothing needs to be inserted into the DOM. But, if it is true then you have an overhead of inserting the - possibly quite complicated - element into the DOM. – Mawg Commented Feb 15, 2016 at 8:29
  • "2) ng-if will create/destroy scope when it evaluates to true/false. If you have a controller attached to the ng-if, that controller code will get executed every time the " – Nate Anderson Commented Oct 8, 2017 at 0:24
Add a comment | 39

The answer is not simple:

It depends on the target machines (mobile vs desktop), it depends on the nature of your data, the browser, the OS, the hardware it runs on... you will need to benchmark if you really want to know.

It is mostly a memory vs computation problem ... as with most performance issues the difference can become significant with repeated elements (n) like lists, especially when nested (n x n, or worse) and also what kind of computations you run inside these elements:

  • ng-show: If those optional elements are often present (dense), like say 90% of the time, it may be faster to have them ready and only show/hide them, especially if their content is cheap (just plain text, nothing to compute or load). This consumes memory as it fills the DOM with hidden elements, but just show/hide something which already exists is likely to be a cheap operation for the browser.

  • ng-if: If on the contrary elements are likely not to be shown (sparse) just build them and destroy them in real time, especially if their content is expensive to get (computations/sorted/filtered, images, generated images). This is ideal for rare or 'on-demand' elements, it saves memory in terms of not filling the DOM but can cost a lot of computation (creating/destroying elements) and bandwidth (getting remote content). It also depends on how much you compute in the view (filtering/sorting) vs what you already have in the model (pre-sorted/pre-filtered data).

Share Improve this answer Follow edited Nov 17, 2015 at 17:08 answered Oct 20, 2015 at 8:21 Christophe Roussy's user avatar Christophe RoussyChristophe Roussy 16.9k5 gold badges92 silver badges85 bronze badges 2
  • 3 Other answers for technical facts. This one for wisdom. You have clearly built non-trivial Angular apps sir! +1 – poshest Commented Sep 4, 2016 at 14:05
  • This problem goes beyond angular, it is a fundamental problem in computer science, there is a point from which on one method is more efficient than the other. Usually this can be found through some benchmarking. So you could even switch between one method and the other depending on the item count ... Similar topic: math.stackexchange.com/questions/1632739/… – Christophe Roussy Commented Oct 17, 2017 at 7:59
Add a comment | 13

One important note:

ngIf (unlike ngShow) usually creates child scopes that may produce unexpected results.

I had an issue related to this and I've spent MUCH time to figure out what was going on.

(My directive was writing its model values to the wrong scope.)

So, to save your hair just use ngShow unless you run too slow.

The performance difference is barely noticable anyway and I am not sure yet on who's favour is it without a test...

Share Improve this answer Follow edited Sep 10, 2014 at 12:52 answered Sep 10, 2014 at 11:43 user2173353's user avatar user2173353user2173353 4,6404 gold badges52 silver badges85 bronze badges 4
  • 8 Using $parent.scopevar in data bindings within an ngIf will rectify things like child scopes issues when using ngIf – m.e.conroy Commented Oct 28, 2014 at 18:58
  • 2 This is not entirely true (the original @user2173353's comment, that is). If you stick to good practices, you won't get into trouble. That's a pretty basic rule: "if there's no dot, you're doing it wrong". See here for a demo of how it works: bit.ly/1SPv4wL. Another great reference (see mistake #2): bit.ly/1QfFeWd > (My directive was writing its model values to the wrong scope.) This is the result of not sticking to the above practice. – piotr.d Commented Jun 26, 2015 at 9:10
  • 1 @piotr.d You are right, but that is not something a beginner may need to focus on and there is another best practice that says that it is better to leave performance improvements for the end (especially performance improvements that may not be improvements in reality). I have seen people putting ngIf everywhere believing that this will improve performance. This is simply not true and one can't say which is best, ngIf or ngShow, without a test or a deep analysis in the particular case. So, I still recommend forgetting about ngIf, until one sees bad performance or knows what he is doing – user2173353 Commented Jun 30, 2015 at 8:36
  • 2 Good point. But using controllerAs makes this a non-issue. See, for instance, John Papa's take on controllerAs and vm. – jsruok Commented Feb 26, 2016 at 9:30
Add a comment | 5

If you use ng-show or ng-hide, the content (e.g. thumbnails from server) will be loaded irrespective of the value of the expression but will be displayed based on the value of the expression.

If you use ng-if, the content will be loaded only if the expression of the ng-if evaluates to truthy.

Using ng-if is a good idea in a situation where you are going to load data or images from the server and show those only depending on user's interaction. This way, your page load will not be blocked by unnecessary network intensive tasks.

Share Improve this answer Follow edited Dec 19 at 8:41 Pang's user avatar Pang 10.1k146 gold badges85 silver badges124 bronze badges answered Sep 20, 2015 at 17:36 appdroid's user avatar appdroidappdroid 5657 silver badges18 bronze badges 1
  • This is especially useful as most browsers will load images even if the CSS hides their DOM containers. They usually just look for the src attribute of the img tag, when present it gets loaded ! – Christophe Roussy Commented Oct 20, 2015 at 8:41
Add a comment | 4

ng-if on ng-include and on ng-controller will have a big impact matter on ng-include it will not load the required partial and does not process unless flag is true on ng-controller it will not load the controller unless flag is true but the problem is when a flag gets false in ng-if it will remove from DOM when flag gets true back it will reload the DOM in this case ng-show is better, for one time show ng-if is better

Share Improve this answer Follow edited Jul 4, 2014 at 4:08 answered Jul 4, 2014 at 3:49 Saad Ahmed's user avatar Saad AhmedSaad Ahmed 1,0779 silver badges9 bronze badges Add a comment | Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.

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

  • The Overflow Blog
  • How developer jobs (and the job market) changed in 2024
  • You should keep a developer’s journal
  • Featured on Meta
  • The December 2024 Community Asks Sprint has been moved to March 2025 (and...
  • Stack Overflow Jobs is expanding to more countries
Visit chat

Linked

0 Hide an HTML element annotated with ng-show from the browser source code on inspect element 0 Do ng-hide and ng-show actually load the element and hide it, or does it only load on ng-show? 434 What is the difference between ng-if and ng-show/ng-hide 20 Angular JS - ng-repeat and loop conditions 0 Best way to show/hide a part based on permission level - Angular JS 7 AngularJs: How to re-attach a handler after using ng-if? 3 How to update ng-if in Angular? 3 When to use ng-if vs ng-show/ng-hide? 3 Get selected option from select with angular JS and ionic 1 How to Hide/Show Drop Down Angular2 Material? See more linked questions 434 What is the difference between ng-if and ng-show/ng-hide 0 ng-show vs ng-if in angularjs 3 AngularJS using ng-if vs ng-show 0 ng-if, ng-show or custom directive? Advice on best practice 0 in this case is better ng-hide/show or ng-if? 3 When to use ng-if vs ng-show/ng-hide? 1 ng-if or ng-show to hide and show a DIV? 1 Do I need NG-IF / NG-SWITCH or NG-SHOW & NG-HIDE? 0 What is the difference between ng-show and ng-if in angular 1.x? 0 Angular ng-hide or ng-show ? why?

Hot Network Questions

  • A puzzle for middle school students: cuboid or slice of cake?
  • Minimum temperature for pocket lighters
  • Consequences of geometric Langlands (or Langlands program) with elementary statements
  • Can I use bootstrapping for small sample sizes to satisfy the power analysis requirements?
  • Elementary consequence of non-abelian class field theory
  • How to design a network and loss function for classes, composed of two other classes?
  • Is Luke 4:8 enjoining to "worship and serve" or serve only
  • Story about a LLM-ish machine trained on Nebula winners, and published under girlfriend's name
  • Are there any responsa on a shul changing davening time on Xmas morning
  • two_input_map_reduce Template Function Implementation in C++
  • What livery is on this F-5 airframe?
  • Makefile for a tiny C++ project
  • Looking for a recent Sci-Fi book where the people live in trees, their body chemistry has been altered to digest the "wrong-handed" local molecules
  • How can jitter be higher than the clock period?
  • Can I bring candles on a European flight?
  • Book where protagonist who repairs vases for a living is contacted by alien race
  • Should a language have both null and undefined values?
  • proper method to reduce 2 inch pipe to 1.5 inch pipe
  • Were there consequences for the reviewers or editors of Andrew Wakefield's MMR/Autism paper?
  • Refereeing a maths paper with individually poor-quality results which nevertheless combine two very different subfields
  • Do you lose the right of attribution if you're charged with a crime?
  • Why was creating sunshields for Webb telescope challenging?
  • How to make the forward slash in a fraction bigger?
  • Wonderful animations on a YouTube channel made with LaTeX
more hot questions Question feed Subscribe to RSS Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-js

Từ khóa » Ng-show Vs Ng-hide Vs Ng-if