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

用AngularJS写

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

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


当前回答

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

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

其他回答

这个答案是为那些不知道如何隐藏一个元素,从.ts文件可见

TS文件

实现OnInit { isHidden:boolean = false; 隐藏(){ 这一点。isHidden = true; } 取消隐藏(){ 这一点。isHidden = false; } }

HTML文件

< div[隐藏]=“isHidden >的< / div > <巴顿(click) =“hide ()“巴顿>隐藏< / > <巴顿(click) =“unHide ()“巴顿> UnHide < - >

<div [hidden]="flagValue">
---content---
</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。

要隐藏和显示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+的方法

如果你的情况是样式为display none,你也可以使用ngStyle指令直接修改显示,我这样做是为了一个引导下拉列表,它的UL被设置为display none。

因此,我创建了一个单击事件,用于“手动”切换UL显示

<div class="dropdown">
    <button class="btn btn-default" (click)="manualtoggle()"  id="dropdownMenu1" >
    Seleccione una Ubicación
    <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" [ngStyle]="{display:displayddl}">
        <li *ngFor="let object of Array" (click)="selectLocation(location)">{{object.Value}}</li>                                
     </ul>
 </div>    

然后在组件上,我有每次切换的showDropDown:bool属性,并基于int设置样式的displayDDL,如下所示

showDropDown:boolean;
displayddl:string;
manualtoggle(){
    this.showDropDown = !this.showDropDown;
    this.displayddl = this.showDropDown ? "inline" : "none";
}