我有一些元素,我想在某些条件下是可见的。
用AngularJS写
<div ng-show="myVar">stuff</div>
如何在Angular 2+中做到这一点?
我有一些元素,我想在某些条件下是可见的。
用AngularJS写
<div ng-show="myVar">stuff</div>
如何在Angular 2+中做到这一点?
当前回答
要隐藏和显示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+的方法
其他回答
你有两个选择:
第一个选项
[style.display]="!isShow ? 'block' : 'none'"
第二个选项
myvariable可以是布尔值
[hidden]="!myVarible"
如果你只是想使用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”-是的,我可以反转,但它更容易出错。(如图所示)更容易思考。
<div [hidden]="myExpression">
myExpression可以设置为true或false
我发现自己处于相同的情况,与我的情况不同,元素是一个伸缩容器。如果不是你的情况,一个简单的工作可以
[style.display]="!isLoading ? 'block' : 'none'"
在我的例子中,由于我们支持的许多浏览器仍然需要供应商前缀来避免问题,我选择了另一种简单的解决方案
[class.is-loading]="isLoading"
哪里的CSS是简单的
&.is-loading { display: none }
将显示的状态留给默认类处理。
使用hidden,就像你用控件绑定任何模型一样,并为它指定css:
HTML:
<input type="button" class="view form-control" value="View" [hidden]="true" />
CSS:
[hidden] {
display: none;
}