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

Ionic 4/5/6如何获取*ngFor循环中每一项的isApproved值并更新数据

实现方案

第一步:改造列表页跳转逻辑

列表页模板中给循环渲染的ion-item绑定点击跳转事件,传递当前条目的id:

<ion-item *ngFor="let box of boxes" (click)="goToEditPage(box.id)">
  <ion-label>{{ box.name }}</ion-label>
  <!-- 列表页仅展示状态,禁止直接操作 -->
  <ion-toggle [checked]="box.isApproved" disabled></ion-toggle>
</ion-item>

列表页TS文件中引入路由模块,编写跳转方法:

import { Router } from '@angular/router';

// 原有变量
isApproved : boolean;
public box: any;
public boxes: any[] = [];

constructor(private router: Router) {}

// 跳转编辑页方法
goToEditPage(boxId: number|string) {
  this.router.navigate(['/box-edit'], { queryParams: { id: boxId } });
}

第二步:新增状态编辑页

可以通过Ionic CLI快速生成页面:ionic g page box-edit

编辑页模板代码

<ion-header>
  <ion-toolbar>
    <ion-title>调整审核状态</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <ion-item>
    <ion-label>条目名称:{{ currentBox.name }}</ion-label>
  </ion-item>
  <ion-item class="ion-margin-top">
    <ion-label>审核通过</ion-label>
    <ion-toggle [(ngModel)]="currentBox.isApproved" (ionChange)="syncToDb()"></ion-toggle>
  </ion-item>
  <ion-button expand="block" class="ion-margin-top" (click)="backToList()">返回列表</ion-button>
</ion-content>

编辑页逻辑代码

import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
// 若有封装好的接口服务可替换HttpClient直接调用对应方法

export class BoxEditPage implements OnInit {
  currentBox = {
    id: null,
    name: '',
    isApproved: false
  }

  constructor(
    private route: ActivatedRoute,
    private http: HttpClient,
    private router: Router
  ) {}

  ngOnInit() {
    // 获取路由传递的条目id
    const targetId = this.route.snapshot.queryParams['id'];
    if(targetId) {
      // 请求后端接口拉取当前条目最新数据
      this.http.get(`你的数据查询接口地址/${targetId}`).subscribe((res: any) => {
        this.currentBox = res;
      })
    }
  }

  // toggle触发时同步更新后端数据
  syncToDb() {
    const updateParams = {
      id: this.currentBox.id,
      isApproved: this.currentBox.isApproved
    }
    this.http.put('你的状态更新接口地址', updateParams).subscribe(() => {
      // 可自行新增Toast提示更新成功
      console.log('状态更新完成')
    })
  }

  // 返回列表页,建议返回后刷新列表数据保证状态同步
  backToList() {
    this.router.navigate(['/列表页路由地址']);
  }
}

补充说明

  • 若不想用queryParams传参,可将编辑页路由配置为动态参数格式path: 'box-edit/:id',跳转时调用this.router.navigate(['/box-edit', boxId]),参数获取改为this.route.snapshot.params['id']即可
  • 编辑页使用ngModel双向绑定需要先在对应模块的imports数组中引入FormsModule
  • 列表页返回后重新拉取boxes数组的全量数据,可避免前端展示与后端数据不一致的问题

内容的提问来源于stack exchange,提问作者pixel draw solutions

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:45:01