当青睐NG-如果与NG-显示/ NG隐藏? [英] When to favor ng-if vs. ng-show/ng-hide?
问题描述
据我所知, NG-节目
和 NG-隐藏
影响类的元素和<$设置C $ C> NG-如果控制元素是否呈现为DOM的一部分。
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.
现就选择有指导 NG-如果
在 NG-节目
/ NG-隐藏
或反之亦然?
Are there guidelines on choosing ng-if
over ng-show
/ng-hide
or vice-versa?
推荐答案
在你的使用情况取决于但总结的区别:
Depends on your use case but to summarise the difference:
-
NG-如果
从DOM删除元素。这意味着所有的处理程序或其他任何连接到这些因素都将丢失。例如,如果你绑定一个click处理子元素,当NG-如果
的值为false之一,该元素将被从DOM删除,你的点击处理程序将无法正常工作更多的,即使在NG-如果
后计算为true,并显示该元素。您将需要重新安装的处理程序。 -
NG-显示/ NG隐藏
不会删除DOM元素。它使用CSS样式隐藏/显示内容(注:您可能需要添加自己的类)。这种方式被装的孩子,你的处理程序也不会丢失。 -
NG-如果
创建一个子范围,而NG-显示/ NG隐藏
不
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, whenng-if
evaluates to false, that element will be removed from DOM and your click handler will not work any more, even afterng-if
later evaluates to true and displays the element. You will need to reattach the handler.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.ng-if
creates a child scope whileng-show/ng-hide
does not
元素不在DOM中有较少的性能影响,并使用当你的Web应用程序可能会出现更快NG-如果
相比,纳克-show / NG隐藏
。根据我的经验,不同的是可以忽略不计。动画同时使用NG-显示/ NG隐藏和NG-IF时,与这两个角文档中的例子是可能的。
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.
最后,你需要回答的问题是你是否可以从DOM元素删除或不?
Ultimately, the question you need to answer is whether you can remove element from DOM or not?
这篇关于当青睐NG-如果与NG-显示/ NG隐藏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!