Ionic 6 中如何通过Input()动态设置ngFor的迭代数组
该方案完全可行,无需为每个页面单独编写重复的列表代码,你现有写法的核心问题是Angular模板不支持通过变量名字符串直接读取组件实例的属性,需要做一层映射处理,具体实现可以参考以下两种方案:
方案1:通过字符串标识映射对应数组(符合你现有思路)
第一步:组件类中定义映射关系
在你的列表复用组件的ts文件中,定义存储所有页面对应数组的映射对象,同时接收传入的currentPage参数:
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-common-list', templateUrl: './common-list.component.html' }) export class CommonListComponent { // 接收传入的页面标识字符串 @Input() currentPage: string = ''; // 定义所有页面对应的数组映射,可按需扩展key值 pageDataMap: Record<string, any[]> = { home: [], category: [], mine: [] } // 后续可以根据currentPage的值,动态请求对应数据赋值给pageDataMap对应的key即可 }
第二步:修改模板中ngFor的写法
把你现有模板中ngFor的表达式改为从映射对象中取对应数组,同时加空值保护避免报错:
<div scrollY="true" height="100px"> <ion-list> <!-- 从映射对象中取当前页面对应的数组,空值默认返回空数组避免报错 --> <ion-item *ngFor="let item of pageDataMap[currentPage] ?? []" > <ion-label class="ion-text-wrap"> {{item.name}} <br> <ion-text> </ion-text> </ion-label> <ion-button fill="solid" id="single-restaurant" (click)="goToNextPage()"> <ion-icon name="arrow-forward-circle-outline"> </ion-icon> </ion-button> </ion-item> </ion-list> </div>
方案2:直接传入数组(更推荐,灵活度更高)
不需要传字符串标识,直接将父组件需要渲染的数组作为Input参数传给列表组件,适配所有无固定数组名的场景:
子组件ts修改
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-common-list', templateUrl: './common-list.component.html' }) export class CommonListComponent { // 直接接收要迭代的数组 @Input() dataList: any[] = []; }
子组件模板修改
<ion-item *ngFor="let item of dataList ?? []" > <!-- 其余列表内容保持不变 --> </ion-item>
父组件调用示例
HomePage中调用时直接传入home数组即可:
<!-- HomePage模板中调用公共列表组件 --> <app-common-list [dataList]="home"></app-common-list>
其他页面调用时只需要替换传入的数组即可,完全不需要修改列表组件的代码。
内容的提问来源于stack exchange,提问作者dude
相关产品推荐
相关产品推荐

