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

用AngularJS写

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

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


当前回答

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

display: flex;

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

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

其他回答

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

display: flex;

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

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

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

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

使用[ngStyle]

[ngStyle]="{'visibility': my-flag ? 'visible' : 'hidden'}"

在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。

你有两个选择:

第一个选项

[style.display]="!isShow ? 'block' : 'none'"

第二个选项

myvariable可以是布尔值

[hidden]="!myVarible"