gpt4 book ai didi

angular - 显示:none and *ngIf = 'false' ?有什么区别

转载 作者:太空狗 更新时间:2023-10-29 17:06:42 25 4
gpt4 key购买 nike

display:none 是 css 表。它
将从 DOM 树中删除元素。ngIf = 'false' 还会从 DOM 树中删除元素。它们有什么区别?

最佳答案

display:none

From MDN Web Docs

The value none lets you turn off the display of an element; when you use none, all descendant elements also have their display turned off. The document is rendered as though the element doesn't exist in the document tree.

但是当使用开发工具查看页面的 DOM 时,元素仍然确实存在在 DOM 树中。这意味着元素不会从 DOM 树中完全删除。


*ngIf="false"

从 DOM 树中完全删除元素。因此,在页面呈现方面,与 display:none 相比,使用 *ngIf="false"> 通过快速页面呈现提供更好的性能。

From Angular Guide

The ngIf directive doesn't hide elements with CSS. It adds and removes them physically from the DOM. Confirm that fact using browser developer tools to inspect the DOM.

When the condition is false, NgIf removes its host element from the DOM, detaches it from DOM events (the attachments that it made), detaches the component from Angular change detection, and destroys it. The component and DOM nodes can be garbage-collected and free up memory.


下面的图片会很好地描述它们

1) 不使用 display:none*ngIf="false"

enter image description here

2) 使用 display:none*ngIf="false"

enter image description here


Comparison of hiding (display:none) vs removing (*ngIf='false')

From Angular Guide

The difference between hiding and removing doesn't matter for a simple paragraph. It does matter when the host element is attached to a resource intensive component. Such a component's behavior continues even when hidden. The component stays attached to its DOM element. It keeps listening to events. Angular keeps checking for changes that could affect data bindings. Whatever the component was doing, it keeps doing.

Although invisible, the component—and all of its descendant components—tie up resources. The performance and memory burden can be substantial, responsiveness can degrade, and the user sees nothing.

On the positive side, showing the element again is quick. The component's previous state is preserved and ready to display. The component doesn't re-initialize—an operation that could be expensive. So hiding and showing is sometimes the right thing to do.

But in the absence of a compelling reason to keep them around, your preference should be to remove DOM elements that the user can't see and recover the unused resources with a structural directive like NgIf .

These same considerations apply to every structural directive, whether built-in or custom. Before applying a structural directive, you might want to pause for a moment to consider the consequences of adding and removing elements and of creating and destroying components.

希望这能帮助您理解它们之间的区别。

关于angular - 显示:none and *ngIf = 'false' ?有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50558124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com