You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Ionic框架下每个ion-card实现独立的toggle切换效果

问题原因

你现在所有ion-toggle都绑定了组件全局唯一的deviceStatus变量,修改任意一个toggle都会同步修改这个全局变量,所以所有绑定了这个变量的toggle都会同步变化。

修改方案

1. 修改TS文件逻辑

  • 移除全局的deviceStatus变量,改为给每个device对象单独挂载开关状态
  • 改造状态变更回调方法,支持接收当前操作的设备对象
const TOKEN_KEY = 'CapacitorStorage.user-token'
@Component({
    selector: 'app-tabhome',
    templateUrl: './tabhome.page.html',
    styleUrls: ['./tabhome.page.scss'],
})
export class TabhomePage implements OnInit, AfterViewInit {
    // 移除原来的全局deviceStatus变量
    public data: any;

    ngOnInit() {
        // 本地提供的json文件
        fetch('./assets/data/tabHomeData.json').then(res => res.json())
        .then(res => {
            // 遍历所有设备,给每个设备添加独立的开关状态,用json里的state字段初始化
            res.rooms.forEach(room => {
                room.devices.forEach(device => {
                    device.isOn = device.state === 'ON';
                })
            })
            this.data = res
        });

        const headerHeight = isPlatform('ios') ? 44 : 56
        this.document.documentElement.style.setProperty(
            '--header-position',
            `calc(env(safe-area-inset-top) + ${headerHeight}px)`
        )
    }

    // 回调方法接收当前操作的设备对象
    deviceStatusChange(device: any){
        // 可选:同步更新device的state字段和开关状态一致
        device.state = device.isOn ? 'ON' : 'OFF';
        console.log(`${device.name} toggle switch : `+ device.isOn);
    }

    ngAfterViewInit() {
        this.lists.changes.subscribe((_) => {
            this.listElements = this.lists.toArray()
        })
    }
}

2. 修改HTML模板绑定逻辑

将ion-toggle的绑定从全局变量改为每个device自己的isOn属性,同时把当前device传递给回调方法:

<ion-grid>
    <ion-row>
        <ion-col *ngFor="let device of individual_room.devices">
            <ion-card>
                <ion-col><img src="assets/icon/favicon.png"/></ion-col>
                <ion-card-content>
                <ion-card-title>
                    {{ device.name }} <ion-badge item-end>{{ device.company }} </ion-badge>
                </ion-card-title>
                <!-- 修改绑定对象和回调传参 -->
                <ion-toggle [(ngModel)]="device.isOn" (ionChange)="deviceStatusChange(device)"></ion-toggle>
                </ion-card-content>
            </ion-card>
        </ion-col>
    </ion-row>
</ion-grid>

修改完成后每个toggle的状态都和当前设备的独立属性绑定,互相之间不会产生影响,原有CSS逻辑无需调整。

内容的提问来源于stack exchange,提问作者Pritesh Bhate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 16:54:08