Ionic Angular中如何根据选中项传递JSON数据到模态框
Ionic-Angular 点击列表项传递数据到模态框的实现方案
你的代码目前有几个关键问题需要调整:
- 模态框被放在
*ngFor循环里,会为每个列表项生成一个模态框,完全没必要 - 没有触发模态框的点击事件,也没有存储点击选中的物品数据
- 模态框内容区域没有绑定数据的逻辑
下面是修改后的完整代码,直接替换原代码即可实现需求:
修改后的 home.page.html
<h1 style="font-size:large; text-align: center; color:darkblue; padding:10px 10px 10px 10px ">Search for your fav Game!!</h1> <div style="display: grid; grid-template-columns: repeat(2, 1fr); align-items: center; justify-content: center; "> <div style="justify-content: center;text-align: center; " *ngFor="let item of results "> <ion-card style="padding-bottom:10px;justify-content: center;" (click)="openModal(item)"> <ion-img src="{{item.Thumbnail_Large}}" style="margin:20px;"> </ion-img> <ion-text style="font-size:x-small; color:darkblue; font-weight: bold; ">{{item.Title}}</ion-text><br> <ion-text style="color: orange;font-size:large;margin-bottom: 20%; ">{{item.Rating}}</ion-text> </ion-card> </div> </div> <!-- 把模态框移到循环外面,只保留一个 --> <ion-modal [isOpen]="isModalOpen"> <ng-template> <ion-header> <ion-toolbar> <ion-title>{{selectedItem?.Title}}</ion-title> <ion-buttons slot="end"> <ion-button (click)="setOpen(false)">Close</ion-button> </ion-buttons> </ion-toolbar> </ion-header> <ion-content class="ion-padding"> <!-- 展示选中物品的全部信息 --> <ion-img src="{{selectedItem?.Thumbnail_Large}}" style="margin:20px;"></ion-img> <p><strong>评分:</strong>{{selectedItem?.Rating}}</p> <!-- 这里可以继续添加其他字段,比如描述、发布日期等,根据你的JSON结构调整 --> <p><strong>描述:</strong>{{selectedItem?.Description}}</p> </ion-content> </ng-template> </ion-modal>
修改后的 home.page.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'] }) export class HomePage implements OnInit { isModalOpen = false; results: any; selectedItem: any; // 新增变量存储选中的物品 constructor() {} ngOnInit(){ fetch('./assets/inputFile/input.json') .then(res => res.json()) .then(json => { console.log('results::',json); this.results=json; }); } setOpen(isOpen: boolean) { this.isModalOpen = isOpen; } // 新增打开模态框的方法,接收点击的物品数据 openModal(item: any) { this.selectedItem = item; // 存储选中的物品 this.setOpen(true); // 打开模态框 } }
关键修改说明:
- 点击事件绑定:给
ion-card添加(click)="openModal(item)",点击时把当前物品传入方法 - 模态框移到循环外:避免生成重复模态框,只维护一个实例
- 新增选中物品变量:用
selectedItem存储点击的物品数据,供模态框使用 - 模态框内容绑定:在模态框里通过
selectedItem?.字段名的方式展示物品信息(?.是Angular的安全导航操作符,避免数据未加载时报错) - 动态模态框标题:把模态框标题改成选中物品的标题,更直观
内容的提问来源于stack exchange,提问作者Alice Ramadan
相关产品推荐
相关产品推荐

