【问题标题】:Keep active state button ngClass / ngFor Bootstrap 4保持活动状态按钮 ngClass / ngFor Bootstrap 4
【发布时间】:2018-05-16 23:35:58
【问题描述】:

我正在使用一些按钮来过滤数据,我想知道如何保持该按钮的活动状态或根据当时激活的过滤器分配样式,我该如何实现?

我的堆栈闪电战:https://stackblitz.com/edit/query-collections-in-angularfire2

<button *ngFor="let categoria of categorias" (click)="filtrarData(categoria.nombre)" class="btn btn-outline-primary btn-sm mx-1">{{ categoria.nombre }}</button>

【问题讨论】:

    标签: angular bootstrap-4


    【解决方案1】:

    您可以为此使用 ngClass

        <button 
          class="btn"
          *ngFor="let categoria of categorias" 
          (click)="filtrarData(categoria.nombre)"
          [ngClass]="categoria.selected ? 'activeButton' : 'normalButotn'>
       </button>
    

    【讨论】:

    • 我试过了,但它不会对状态产生任何变化
    • 因此,如果您想在更改状态时刷新 UI,那么您需要以不可变的方式进行更新,以便组件生命周期开始,组件重新渲染并刷新 UI。
    【解决方案2】:

    你可以试试ngClass。当所选值等于HTML中的值时。添加active 类。 当您单击重置时。只需删除currentValue

    HTML:
     [ngClass]="{'active': categoria.nombre === currentValue}"
    
    Component.ts:
    
    filtrarData(categoriaToFilter: string) {
      this.currentValue = categoriaToFilter;
    }
    
    getAvisos() {
      this.currentValue = '';
    }
    

    别忘了导入 Renderer2。

    【讨论】:

    • 它工作正常但是当我按下另一个重置按钮时有一个细节,也就是说,当我不在那个状态时它仍然被激活。当我已经离开活动时,有什么办法可以取消它?
    • 嗨@PacoZevallos。单击重置按钮或其他选项卡时,我更改了删除活动类的答案
    • Error: Function Query.where() requires a valid third argument, but it was undefined.
    • 嗨@PacoZevallos,只需在函数filtrarData() 中删除event。现在效果很好
    猜你喜欢
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多