Angular 2+:控制能见度

时间:2018-02-06 14:35:25

标签: angular model-view-controller

我喜欢用按钮控制某些内容的可见性(单击它以显示内容)。 我能想到的最好的是用布尔变量来控制它。

<button (click)="show=true">ShowIt</button>
<div *ngIf="show == true">{{ content }}</div>

show : boolean = false;
content : string = "blablabla"

我觉得那很笨拙。有更优雅的方式吗?

修改

这不是关于如何隐藏某些东西。更重要的是我真的需要一个额外的变量。

1 个答案:

答案 0 :(得分:1)

我认为使用*ngIf完全没问题。你可以,例如实现切换:

<button (click)="show = !show">Toggle content</button>
<div *ngIf="show">{{content}}</div>

来自docs

  

ngIf指令的最常见用法是有条件地显示   如本例所示的内联模板:

@Component({
  selector: 'ng-if-simple',
  template: `
    <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
    show = {{show}}
    <br>
    <div *ngIf="show">Text to show</div>
`
})
class NgIfSimple {
  show: boolean = true;
}

看起来像你的东西。