我有一些元素,我想在某些条件下是可见的。

用AngularJS写

<div ng-show="myVar">stuff</div>

如何在Angular 2+中做到这一点?


当前回答

在Angular文档https://angular.io/guide/structural-directives#why-remove-rather-than-hide上有两个例子

指令可以通过将其显示样式设置为none来隐藏不需要的段落。

<p [style.display]="'block'">
  Expression sets display to "block".
  This paragraph is visible.
</p>

<p [style.display]="'none'">
  Expression sets display to "none".
  This paragraph is hidden but still in the DOM.
</p>

你可以使用[style。display]="'block'"来替换ngShow和[style.]display]="'none'"替换ngHide。

其他回答

抱歉,我不同意将绑定为hidden,因为在使用Angular 2时,它被认为是不安全的。这是因为隐藏样式可以很容易地覆盖,例如使用

display: flex;

建议使用*ngIf,这样更安全。更多细节,请参考Angular官方博客。使用Angular 2要避免的5个新手错误

<div *ngIf="showGreeting">
   Hello, there!
</div>

在Angular文档https://angular.io/guide/structural-directives#why-remove-rather-than-hide上有两个例子

指令可以通过将其显示样式设置为none来隐藏不需要的段落。

<p [style.display]="'block'">
  Expression sets display to "block".
  This paragraph is visible.
</p>

<p [style.display]="'none'">
  Expression sets display to "none".
  This paragraph is hidden but still in the DOM.
</p>

你可以使用[style。display]="'block'"来替换ngShow和[style.]display]="'none'"替换ngHide。

隐藏属性可以用于此

[hidden]="!myVar"

另请参阅

https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden

问题

hidden有一些问题,因为它可能与CSS的display属性冲突。

看看Plunker例子中的一些没有被隐藏,因为它有一个样式

:host {display: block;}

集。(这可能在其他浏览器中表现不同-我用Chrome 50测试)

解决方案

你可以通过添加来修正它

[hidden] { display: none !important;}

到index.html中的全局样式。

另一个陷阱

hidden="false"
hidden="{{false}}"
hidden="{{isHidden}}" // isHidden = false;

是一样的

hidden="true"

并且不会显示元素。

Hidden ="false"将分配字符串"false",该字符串被认为是真值。 只有值为false或删除属性才会实际生成元素 可见。

使用{{}}也会将表达式转换为字符串,不会像预期的那样工作。

只有绑定[]才会像预期的那样工作,因为这个false被赋值为false而不是“false”。

*ngIf与[hidden]

*ngIf有效地从DOM中删除了它的内容,而[hidden]修改了display属性,只是指示浏览器不显示内容,但DOM仍然包含它。

在引导4.0中,类"d-none" = "display: none!important;"

<div [ngClass]="{'d-none': exp}"> </div>

使用[hidden]属性:

[hidden]="!myVar"

或者你可以使用*ngIf

*ngIf="myVar"

这是显示/隐藏元素的两种方法。唯一的区别是:*ngIf将从DOM中删除元素,而[hidden]将告诉浏览器使用CSS display属性显示/隐藏元素,将元素保留在DOM中。