在Angular 7中如何显示/隐藏一个div

19

我正在尝试使用ng-model和ng-hide在Angular 7中显示/隐藏一个div,但它不起作用。

使用ng-model设置表达式的button来显示/隐藏

    <button type="checkbox" ng-model="show" >show/hide</button>

div用于显示/隐藏,使用ng-hide隐藏div

<div class="row container-fluid" ng-hide="show" id="divshow" >
  Div Content
</div>    
</body>
</html>

我尝试过使用ng-modelng-hide,但仍然无法正常工作。请提供解决方案。


1
请提供一个 [mcve]。 - Prerak Sola
7个回答

20

在您的HTML中

<button (click)="toggleShow()" type="checkbox" >show/hide</button>

<div *ngIf="isShown" class="row container-fluid"  id="divshow" >
Div Content

</div>

在您的组件类中添加以下内容:

isShown: boolean = false ; // hidden by default


toggleShow() {

this.isShown = ! this.isShown;

}

13

请尝试以下解决方案:

解决方案1:

<div *ngIf="show" class="row container-fluid"  id="divshow" >
        Div Content
    </div>

解决方案2:

<div [hidden]="!show" class="row container-fluid"  id="divshow" >
            Div Content
        </div>

1
两者之间有很大的区别。ngIf会删除并创建元素,而[hidden]则不会。 - robBerto

4
你可以使用<div *ngIf="show",并在.ts文件中使用布尔值,当按钮被触发时你可以更改该值。

3
如果您使用的是 type='checkbox',则可以使用 change 事件处理程序。
<input type="checkbox" (change)="show = !show" ng-model="show" />
Div to Show/Hide

<div class="row container-fluid" *ngIf="show" id="divshow" >
Div Content
</div>

Stackblitz 演示


我可以问你一个关于你的代码的问题吗? - elodie

1
最佳方式:
<input type="checkbox" (change)="show = !show" ng-model="show"/>
show/hide

<div class="row container-fluid" [hidden]="!show" id="divshow" >
Div Content
</div>

0

这里有一个巧妙的方法来隐藏/移除项目,特别是当有一系列项目时非常方便。

请注意它如何利用Angular的模板变量(#ListItem)。

<ng-container *ngFor="let item of list">
  <div #ListItem>
    <button (click)="close(ListItem)">
  </div>
</ng-container>

  close(e: HTMLElement) {
    e.remove();
  }

-1

在你的ts文件中,你应该使用一个标志(flag),默认情况下标志为false。

<button type="checkbox" (click)="flag= !flag">{{falg=== true ? 'Show' : 'Hide'}}</button>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接