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

用AngularJS写

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

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


当前回答

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

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

其他回答

要隐藏和显示div在按钮上单击angular 6。

Html代码

<button (click)="toggleElement()">FormatCell</button>
<div class="ruleOptionsPanel" *ngIf="isShow">
   <table>
      <tr>
         <td>Name</td>
         <td>Ram</td>
      </tr>
   </table>
</div>

AppComponent。ts代码

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent{
   isShow=false;
   toggleElement():void
   {
      this.isShow = !this.isShow
   }
}

这适用于我,它是一种替代ng-hide和ng-show在angular2+的方法

对于其他无意中遇到这个问题的人来说,这就是我如何做到的。

import {Directive, ElementRef, Input, OnChanges, Renderer2} from "@angular/core";

@Directive({
  selector: '[hide]'
})
export class HideDirective implements OnChanges {
  @Input() hide: boolean;

  constructor(private renderer: Renderer2, private elRef: ElementRef) {}

  ngOnChanges() {
    if (this.hide) {
      this.renderer.setStyle(this.elRef.nativeElement, 'visibility', 'hidden');
    } else {
      this.renderer.setStyle(this.elRef.nativeElement, 'visibility', 'visible');
    }
  }
}

我使用“可见性”是因为我想保留元素所占据的空间。如果你不希望这样做,你可以使用'display'并将其设置为'none';

你可以将它绑定到你的html元素,动态的或者非动态的。

<span hide="true"></span>

or

<span [hide]="anyBooleanExpression"></span>

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

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

如果你正在使用Bootstrap是这样简单:

<div [class.hidden]="myBooleanValue"></div>

我发现自己处于相同的情况,与我的情况不同,元素是一个伸缩容器。如果不是你的情况,一个简单的工作可以

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

在我的例子中,由于我们支持的许多浏览器仍然需要供应商前缀来避免问题,我选择了另一种简单的解决方案

[class.is-loading]="isLoading"

哪里的CSS是简单的

&.is-loading { display: none } 

将显示的状态留给默认类处理。