首页 > 解决方案 > 在每个部分应用 ngClass

问题描述

我已经完成了所有 UI 部分的实现。看起来

在此处输入图像描述

我的数据是

public filters = [
    {
      tag: 'Year',
      label: 'year',
      items: [2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020]
    },
    {
      tag: 'Cash On Delivery',
      label: 'cash',
      items: this.truthyFalsy
    },
    {
      tag: 'In stock',
      label: 'stock',
      items: this.truthyFalsy
    }
  ];

我的html代码是

      <div *ngFor="let filter of filters">
        <p ><small>{{filter?.tag}}</small></p>
        <div class="line"></div>
        <div>
          <div class="item" *ngFor="let item of filter?.items">
            <button class="btn" [ngClass]="{'btn-active-1':labelType1 === filter.label  && selectedItem === item }"
              (click)="select(item,filter?.label)">{{item}}</button>
          </div>
        </div>
      </div>

在选定的按钮上,我必须使其处于活动状态。

实际上我的要求是

  1. year section我必须让任何一个人活跃
  2. Cash On delivery我必须让任何一个人活跃
  3. In stock我必须让任何一个人活跃起来

在每个部分中,我必须至少使用一个按钮处于活动状态ngClass

标签: cssangulartypescriptng-class

解决方案


我在Stackblitz上为您创建了一个示例。

您可以使用let i = index按索引选择项目并具有默认选定项目。所以,试试这个来选择每个组中的第一个项目:

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  labelType1: string = "";
  public selectedItem = { year : 0, cash: 0, stock: 0  };
  truthyFalsy: any[] = [true, false];
  public filters = [
    {
      tag: 'Year',
      label: 'year',
      items: [2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020]
    },
    {
      tag: 'Cash On Delivery',
      label: 'cash',
      items: this.truthyFalsy
    },
    {
      tag: 'In stock',
      label: 'stock',
      items: this.truthyFalsy
    }
  ];

  select(index, label){
    this.selectedItem[label] = index;
  }
}
}

app.component.html

<div *ngFor="let filter of filters">
    <p><small>{{filter?.tag}}</small></p>
    <div class="line"></div>
    <div>
        <div class="item" *ngFor="let i=index; let item of filter?.items">
            <button class="btn" [ngClass]="{'btn-active-1': selectedItem[filter.label] === i}" (click)="select(i,filter?.label)">{{item}}</button>
        </div>
    </div>
</div>

推荐阅读