我有一些元素,我想在某些条件下是可见的。
用AngularJS写
<div ng-show="myVar">stuff</div>
如何在Angular 2+中做到这一点?
我有一些元素,我想在某些条件下是可见的。
用AngularJS写
<div ng-show="myVar">stuff</div>
如何在Angular 2+中做到这一点?
当前回答
如果你的情况是样式为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";
}
其他回答
使用hidden,就像你用控件绑定任何模型一样,并为它指定css:
HTML:
<input type="button" class="view form-control" value="View" [hidden]="true" />
CSS:
[hidden] {
display: none;
}
我的问题是显示/隐藏一个垫子的按钮点击使用 < ng-container * ngIf = " myvar# " >。表的“加载”非常慢,在2-3秒内有300条记录。
数据是使用ngOnInit()中的订阅来加载的,并且可以在模板中使用,但是随着行数的增加,模板中表的“加载”变得越来越慢。
我的解决方案是将*ngIf替换为:
< div[风格。显示]= " activeSelected吗?'block': 'none'">
. 现在,当单击按钮时,表立即加载。
如果你的情况是样式为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";
}
对于其他无意中遇到这个问题的人来说,这就是我如何做到的。
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>
如果你正在使用Bootstrap是这样简单:
<div [class.hidden]="myBooleanValue"></div>