【问题标题】:Show Hide a div in angular 7显示以角度 7 隐藏 div
【发布时间】:2019-08-17 21:22:34
【问题描述】:

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

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

    <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 仍然无法正常工作。 请提供解决方案

【问题讨论】:

标签: javascript angular angular7 ng-show


【解决方案1】:

这是一种隐藏/删除项目的巧妙方法,如果有项目列表,则特别方便。

注意它如何利用Angular's template variables (#ListItem)。

<ng-container *ngFor="let item of list">
  <div #ListItem>
    <button (click)="close(ListItem)">
  </div>
</ng-container>
  close(e: HTMLElement) {
    e.remove();
  }

【讨论】:

    【解决方案2】:

    最好的方法:

    <input type="checkbox" (change)="show = !show" ng-model="show"/>
    show/hide
    
    <div class="row container-fluid" [hidden]="!show" id="divshow" >
    Div Content
    </div>
    

    【讨论】:

      【解决方案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 Demo

      【讨论】:

      • 我可以问你一个关于你的代码的问题吗?
      【解决方案4】:

      你应该在你的 ts 文件中使用一个标志,默认标志为 false

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

      【讨论】:

        【解决方案5】:

        在您的 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;
        
        }
        

        【讨论】:

          【解决方案6】:

          试试这个解决方案:

          解决方案一:

          <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>
          

          【讨论】:

          • 两者有很大区别。 ngIf 删除并创建元素。 [隐藏]没有。
          【解决方案7】:

          您可以使用&lt;div *ngIf="show"

          并在您的 .ts 文件中使用一个布尔值,如果按钮被触发,您可以更改该值

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-12-27
            相关资源
            最近更新 更多