问题描述
我已经完成了所有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>
在选定的按钮上,我必须将其激活。
实际上我的要求是
在每个部分中,我必须使用 ngClass
解决方法
我在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>
,
工作DEMO
单击按钮时,您可以传递项目索引和标签以区分所有类型的部分及其按钮。
/* initialize empty object of selectedItem where we can set key(lable)
and value(index) on each button click from key(label) and value(index)
we can identify the selected button of each section */
selectedItem = {};
select
方法打开按钮,如果用户单击已选择的按钮,它将删除选择的按钮,否则将选择按钮。
select(index,label) {
if(this.selectedItem[label] === index) {
delete this.selectedItem[label]
} else {
this.selectedItem = {
...this.selectedItem,[label]: index
};
}
}
在模板中,您只需通过index
方法传递label
和select
并通过放置[class.btn-active-1]="selectedItem[filter.label] === i"
来添加条件活动类
<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; let i=index">
<button class="btn" [class.btn-active-1]="selectedItem[filter.label] === i"
(click)="select(i,filter?.label)">{{item}}</button>
</div>
</div>
</div>