这是我的角度应用程序中我的垫子卡列表的HTML代码:
<div [ngClass]="verticalResultsBarStyle">
<div class="innerDiv">
<mat-card [ngClass]="barStyle" *ngFor="let card of obs | async | paginate: { id: 'paginator', itemsPerPage: 10, currentPage: currentPage, totalItems: totalItems }" (click)="highlightCard()">
<mat-card-header>
<mat-card-title>{{card[0].title}}</mat-card-title>
<mat-card-subtitle>{{card[0].subtitle}}</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
<p>{{card[0].info1}}</p>
<p>{{card[0].info2}}</p>
<p>{{card[0].info3}}</p>
<p>{{card[0].info4}}</p>
<p>{{card[0].info5}}</p>
</mat-card-content>
</mat-card>
<pagination-controls (pageChange)="OnPaginateChange($event)" id="paginator"></pagination-controls>
</div>
</div>这是CSS:
.verticalResultsBarContainerEnabled {
background-color: #eeeeee;
width: 16%;
float: right;
overflow: visible;
}
.verticalResultsBarContainerDisabled {
display: none;
}
.card {
margin-left: 10px;
margin-right: 10px;
margin-bottom: 10px;
}
.cardHighlight {
margin-left: 10px;
margin-right: 10px;
margin-bottom: 10px;
background-color: #c12400;
color: white;
}
.innerDiv {
height: 755px;
overflow: auto;
}
.paginator {
margin: auto;
width: 92%;
}最后,这是TS的一个片段:
highlightCard() {
if (this.barStyle === 'card') {
this.barStyle = 'cardHighlight';
} else {
this.barStyle = 'card';
}
}我会点击一个单一的垫卡,并只高亮选定的垫卡,但当我点击一张单卡,整个列表改变颜色。我怎么才能解决呢?
发布于 2020-02-28 09:28:07
您需要为您的每张卡使用索引。你的问题很正常。
我看barStyle是你所有牌的通用。当您的卡来自后端时,您需要更新每一张卡的barStyle。
首先,在您的.ts中:
service.subscribe(cards => {
let i = 0
cards.forEach(card => {
this.barStyle[i] = // your default barStyle;
i++;
});如果您对每辆车都有一个id,那么您可以避免使用i。然后,在模板中:
<mat-card [ngClass]="barStyle[i]" *ngFor="let card of obs; let i = index | async | paginate: { id: 'paginator', itemsPerPage: 10, currentPage: currentPage, totalItems: totalItems }" (click)="highlightCard(i)">我看到您在模板中使用异步函数。所以,在ts中,您期望和可观察到的。若要更新每张卡的样式,您需要在您的服务和更新对象上订阅。因此,需要做一些更改:
卡:可观察的将变成卡: Card[];
loadingData = true;
请按以下方式呼叫服务:
getData() {
this.loadingData = true;
service().subscribe(cards => {
cards.forEach(card => {
this.barStyle[card.id] = // your default barStyle;
this.cards = cards;
this.loadingData = false; // this is set false only after data is loaded
});
}
highlightCard(id: number) {
if (this.barStyle[id] === 'card') {
this.barStyle[id] = 'cardHighlight';
} else {
this.barStyle[id] = 'card';
}
}在模板中:
<mat-card ***ngIf="!loadingData"**
[ngClass]="barStyle[card.id]"
*ngFor="let card of obs | async |
paginate: { id: 'paginator',
itemsPerPage: 10,
currentPage: currentPage,
totalItems: totalItems }"
(click)="highlightCard(card.id)">有些情况下,模板会在加载数据之前呈现,因此需要使用布尔值来等待。
**为了保持代码整洁,您可以使用在.ts*中初始化的变量进行分页
https://stackoverflow.com/questions/60448626
复制相似问题