我有一些元素,我想在某些条件下是可见的。
用AngularJS写
<div ng-show="myVar">stuff</div>
如何在Angular 2+中做到这一点?
我有一些元素,我想在某些条件下是可见的。
用AngularJS写
<div ng-show="myVar">stuff</div>
如何在Angular 2+中做到这一点?
当前回答
如果你只是想使用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”-是的,我可以反转,但它更容易出错。(如图所示)更容易思考。
其他回答
如果你只是想使用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”-是的,我可以反转,但它更容易出错。(如图所示)更容易思考。
在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。
这个答案是为那些不知道如何隐藏一个元素,从.ts文件可见
TS文件
实现OnInit { isHidden:boolean = false; 隐藏(){ 这一点。isHidden = true; } 取消隐藏(){ 这一点。isHidden = false; } }
HTML文件
< div[隐藏]=“isHidden >的< / div > <巴顿(click) =“hide ()“巴顿>隐藏< / > <巴顿(click) =“unHide ()“巴顿> UnHide < - >
[隐藏]= " yourVariable " 或 [style.display] = " ! isShow ?'block': 'none'"
抱歉,我不同意将绑定为hidden,因为在使用Angular 2时,它被认为是不安全的。这是因为隐藏样式可以很容易地覆盖,例如使用
display: flex;
建议使用*ngIf,这样更安全。更多细节,请参考Angular官方博客。使用Angular 2要避免的5个新手错误
<div *ngIf="showGreeting">
Hello, there!
</div>