我有一些元素,我想在某些条件下是可见的。
用AngularJS写
<div ng-show="myVar">stuff</div>
如何在Angular 2+中做到这一点?
我有一些元素,我想在某些条件下是可见的。
用AngularJS写
<div ng-show="myVar">stuff</div>
如何在Angular 2+中做到这一点?
当前回答
处理这个问题的最好方法是使用ngIf 因为这会阻止元素在前端渲染,
如果你使用[hidden]="true"或style hide [style. "它将只隐藏在前端的元素,并且人们可以更改它的值并轻松查看它, 在我看来,最好的隐藏元素的方法是ngIf
<div *ngIf="myVar">stuff</div>
如果你有多个元素(需要实现else also),你可以使用<ng-template>选项
<ng-container *ngIf="myVar; then loadAdmin else loadMenu"></ng-container>
<ng-template #loadMenu>
<div>loadMenu</div>
</ng-template>
<ng-template #loadAdmin>
<div>loadAdmin</div>
</ng-template>
ng模板示例代码
其他回答
如果你只是想使用AngularJS提供的对称的隐藏/显示指令,我建议写一个属性指令来简化模板(用Angular 7测试):
import { Directive, Input, HostBinding } from '@angular/core';
@Directive({ selector: '[shown]' })
export class ShownDirective {
@Input() public shown: boolean;
@HostBinding('attr.hidden')
public get attrHidden(): string | null {
return this.shown ? null : 'hidden';
}
}
其他许多解决方案都是正确的。你应该尽可能使用*ngIf。使用hidden属性可能会应用意想不到的样式,但除非您正在为其他人编写组件,否则您可能知道它是否是。因此,为了让这个显示的指令工作,你还需要确保你添加:
[hidden]: {
display: none !important;
}
到你的全球风格某处。
你可以像这样使用指令:
<div [shown]="myVar">stuff</div>
用这样对称的(和相反的)版本:
<div [hidden]="myVar">stuff</div>
在should - yous should后面加一个前缀,比如so [acmeshowwn]和just [shows]。
我使用显示属性指令的主要原因是为了将AngularJS代码转换为Angular - and——当被隐藏的内容包含导致XHR往返的容器组件时。我不直接用[hidden]="!myVar”是经常足够复杂,像:[hidden]="!(myVar || yourVar) && anotherVar”-是的,我可以反转,但它更容易出错。(如图所示)更容易思考。
使用hidden,就像你用控件绑定任何模型一样,并为它指定css:
HTML:
<input type="button" class="view form-control" value="View" [hidden]="true" />
CSS:
[hidden] {
display: none;
}
<div [hidden]="myExpression">
myExpression可以设置为true或false
根据ngShow和ngHide的Angular 1文档,这两个指令都会根据指令的条件为元素添加css样式display: none !important;(对于ngShow,为false值添加css,而对于ngHide,为true值添加css)。
我们可以使用Angular 2的ngClass指令来实现这个行为:
/* style.css */
.hide
{
display: none !important;
}
<!-- old angular1 ngShow -->
<div ng-show="ngShowVal"> I'm Angular1 ngShow... </div>
<!-- become new angular2 ngClass -->
<div [ngClass]="{ 'hide': !ngShowVal }"> I'm Angular2 ngShow... </div>
<!-- old angular1 ngHide -->
<div ng-hide="ngHideVal"> I'm Angular1 ngHide... </div>
<!-- become new angular2 ngClass -->
<div [ngClass]="{ 'hide': ngHideVal }"> I'm Angular2 ngHide... </div>
注意,对于Angular2中的show行为,我们需要添加!(不是)在ngShowVal之前,对于Angular2中的hide行为,我们不需要添加!(不是)在ngHideVal之前。
如果你的情况是样式为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";
}