【问题标题】:Condition changes in ngClass but class is not updatedngClass 中的条件更改但类未更新
【发布时间】:2019-07-12 04:56:11
【问题描述】:

我正在尝试隐藏并显示图标的单击事件上的 div。因为我正在使用带有条件的 ngClass。当条件中的变量发生变化时,类保持不变,它不会更新类。

//html

<div class="column  icon">
    <mat-icon (click)="onIconClick()" id="icon" class="column" [ngStyle]="showpanel ? {'color':'#4ac2f7'}:''">filter_list</mat-icon>
</div>

//隐藏和显示div

<div class="search-box-container" id="filter-tab" [ngClass]="'showpanel' ? 'show' : 'hidden'">
</div>

//点击图标.ts代码

onIconClick() {
    if (this.showpanel) {
      this.showpanel = false;
    } else {
      this.showpanel = true;
    }
    console.log(this.showpanel);
}

【问题讨论】:

  • 你能显示你的css代码吗?

标签: css angular


【解决方案1】:

删除条件(显示面板)单引号

试试这个:

<div class="search-box-container" id="filter-tab" [ngClass]="showpanel ? 'show' : 'hidden'">
</div>

【讨论】:

    【解决方案2】:

    这个[ngClass]="'showpanel' ? 'show' : 'hidden'" 模式将你的showpanel 作为一个字符串,所以它总是被评估为true 并返回'show' 类。删除 single quote mark 并且它应该正确评估

    【讨论】:

      【解决方案3】:

      您尚未在问题中添加 CSS。虽然,我检查了你的代码。您只需要从显示面板中删除引号。 请看下面的代码 -

      在 app.component.html 中

       <button (click)="onIconClick()" id="icon" class="column" [ngStyle]="showpanel ? {'color':'#4ac2f7'}:''">filter_list</button>
      
       <div class="search-box-container" id="filter-tab" [ngClass]="showpanel ? 'show' : 'hidden'">
            filter-tab
       </div>
      

      在你的 aap.component.ts 中

      showpanel = false;
      onIconClick() {
        if (this.showpanel) {
          this.showpanel = false;
        } else {
          this.showpanel = true;
        }
        console.log(this.showpanel);
      }
      

      在你的 app.component.css 中

      .show {
       display: block;
      }
      
      .hidden {
        display: none;
      }
      

      将“div”替换为“mat-icon”

      另外,您可以在此处查看工作示例 - https://stackblitz.com/edit/angular-xsvxd6

      【讨论】:

        【解决方案4】:
        <button (click)="showpanel= !showpanel" id="icon" class="column" [ngStyle]="showpanel ? {'color':'#4ac2f7'}:''">filter_list</button>
        
         <div class="search-box-container" id="filter-tab" [ngClass]="showpanel ? 'show' : 'hidden'">
              filter-tab
         </div>
        

        CSS

        .show {
             display: block;
            }
        
            .hidden {
              display: none;
            }
        

        即使没有 Function,你也可以做同样的事情。

        Stackblitz link here

        如果你想让函数做同样的事情,那么

        onIconClick() {
        this.showpanel =! this.showpanel;
        }
        

        【讨论】:

          猜你喜欢
          • 2014-11-23
          • 1970-01-01
          • 2017-09-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多