我正在嘗試在單擊時選擇類別串列。當我點擊時,背景顏色必須改變,如果我再次點擊同一個,背景必須恢復為默認顏色。如果我沒有選擇任何類別或擁有所選類別的串列,我需要能夠擁有所有類別的串列
我現在的代碼是這樣作業的:如果我點擊卡片,背景顏色會變成粉紅色,如果我再點擊一次,它不會改變,我只能選擇一個專案
page.html
<ion-grid>
<ion-row>
<ion-card
*ngFor="let tag of tags; index as i;"
[ngClass]="{ 'use-pink-background': currentSelected == i}"
(click)="handleClick(i, tag.id)">
<ion-card-header >
<ion-item lines="none">
<p>{{ tag.name_it }}</p>
<span>{{ tag.id }}</span>
</ion-item>
</ion-card-header>
</ion-card>
</ion-row>
</ion-grid>
頁面.scss
.use-pink-background{
--ion-background-color: pink;
}
頁面.ts
constructor(private _mysrvTags: TagsService) { }
ngOnInit() {
this.loadTags();
}
loadTags(){
this._mysrvTags.getTags().subscribe({
next: (data:any)=>{
this.tags = data.taglist
}
})
}
public currentSelected: Number = null;
handleClick(i, tag) {
this.currentSelected = i;
}
我想做這樣的事情:

uj5u.com熱心網友回復:
該問題與您的 ngClass 中的邏輯有關。
當您的問題表明您希望擁有多個專案時,您只是針對單個值進行測驗。
您在 handleClick 中的邏輯也不正確,因為您將值設定為 true 但從未將其設定為 false。這就是為什么您可以選擇一次但不能取消選擇的原因。
您的問題與 Ionic 框架沒有任何關系,而是一個邏輯問題。
因此,為了時間和清晰起見,我將其分解為在 stackblitz 找到的可行解決方案。
應用組件:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
tags=[{
name_it: 'foo1',
id: 'foo1',
},
{
name_it: 'foo2',
id: 'foo2',
},
{
name_it: 'foo3',
id: 'foo3',
}];
currentSelected = new Array(this.tags.length);
handleClick(index: number, id: string) {
// the double bang evaluates null/undefined to falsey
// so you get the initial value set
// the third bang correctly toggles the value
this.currentSelected[index] = !!!this.currentSelected[index];
console.log('tags', this.currentSelected);
}
}
應用程式.html
<div *ngFor="let tag of tags; index as i;"
[ngClass]="{ 'use-pink-background': currentSelected[i]}"
(click)="handleClick(i, tag.id)">
{{tag.name_it}}
</div>
應用程式.css
.use-pink-background{
background-color: pink;
}
以下是在您的代碼中實作但未經測驗的相同內容:page.html
<ion-grid>
<ion-row>
<ion-card
*ngFor="let tag of tags; index as i;"
[ngClass]="{ 'use-pink-background': currentSelected[i] == i}"
(click)="handleClick(i, tag.id)">
<ion-card-header >
<ion-item lines="none">
<p>{{ tag.name_it }}</p>
<span>{{ tag.id }}</span>
</ion-item>
</ion-card-header>
</ion-card>
</ion-row>
</ion-grid>
頁面.ts
constructor(private _mysrvTags: TagsService) { }
currentSelected = [];
ngOnInit() {
this.loadTags();
}
loadTags(){
this._mysrvTags.getTags().subscribe({
next: (data:any)=>{
this.tags = data.taglist;
this.currentSelected = new Array(tags.length);
}
})
}
public currentSelected: Number = null;
handleClick(i, tag) {
// double bang will evaluate null/undefined to falsey
// so the boolean will initialize itself for free
// then the third bang toggles the boolean correctly
this.currentSelected[i] = !!!this.currentSelect[i];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/466894.html
