Html Angular2:条件显示,绑定到 [hidden] 属性 vs. *ngIf 指令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39777990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:52:44  来源:igfitidea点击:

Angular2: conditional display, bind to [hidden] property vs. *ngIf directive

htmlangular

提问by Bing Lu

In Angular2, let's say I want to conditionally display a <div>block. What's the difference between the following two ways.

在 Angular2 中,假设我想有条件地显示一个<div>块。以下两种方式有什么区别。

  1. <div [hidden]=isLoaded>Hello World!</div>where isLoadedis a boolean in corresponding .tsfile.

  2. <div *ngIf=isLoaded>Hello World!</div>

  1. <div [hidden]=isLoaded>Hello World!</div>其中isLoaded是相应.ts文件中的布尔值。

  2. <div *ngIf=isLoaded>Hello World!</div>

I do know that even if the <div>is not shown in the page, 1. still has the <div>in the DOM while 2. doesn't. Are there any other differences? What're the pros and cons of each of them?

我确实知道,即使<div>未显示在页面中,1. 仍然<div>在 DOM 中,而 2. 没有。还有其他区别吗?它们各自的优缺点是什么?

回答by Husein Roncevic

The difference is that *ngIfwill remove the element from the DOM, while [hidden]actually plays with the CSS style by setting display:none. However, the problem with [hidden]is that it can be overiden so the div, as in your case, would be displayed and you would be scratching your head why it doesn't work.

不同之处在于,*ngIf它将从 DOM 中删除元素,而[hidden]实际上通过设置 .css 来处理 CSS 样式display:none。但是,问题[hidden]在于它可以被覆盖,因此div,就像在您的情况下一样,将显示出来,您会摸不着头脑,为什么它不起作用。

To sum things up, *ngIfand [hidden]are notthe same at all. The former removes an element from DOM, while the latter toggles displayCSS property.

总结起来,*ngIf[hidden]根本一样。前者从 DOM 中删除一个元素,而后者切换displayCSS 属性。