简体   繁体   中英

Ionic collection repeat not working

I have an array of objects that I want to loop through in my template and output as cards. I have it working currently using *ngfor and now I want to change it to use collection repeat instead.

Here is my code:

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

import { TowersModel } from '../../app/models/towers-model';

@Component({
  selector: 'page-towers',
  templateUrl: 'towers.html'
})
export class TowersPage {

      towers: any;

    constructor(public navCtrl: NavController){ 

        this.towers = [
            {
                "name" : "Tower 1",
                "image" : "http://placehold.it/350x150"
            },
            {
                "name" : "Tower 2",
                "image" : "http://placehold.it/350x150"
            },
            {
                "name" : "Tower 3",
                "image" : "http://placehold.it/350x150"
            }
        ];
    }
}

Template:

<ion-header>
  <ion-navbar>
    <ion-title>
      Towers
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
    <ion-content>

        <ion-card *ngFor="let tower of towers">
            <img src="{{ tower.image }}" alt="{{tower.name}}">

            <ion-item>
                <h2>{{tower.name}}</h2>
                <p>11 N. Way St, Madison, WI 53703</p>
            </ion-item>

            <ion-item>
                <span item-left>18 min</span>
                <span item-left>(2.6 mi)</span>
                <button ion-button icon-left clear item-right>
                    <ion-icon name="navigate"></ion-icon>
                    Start
                </button>
            </ion-item>
        </ion-card>

    </ion-content>
</ion-content>

So as mentioned this approach works fine. If I try and change it though to use a collection repeat instead like so:

<ion-header>
  <ion-navbar>
    <ion-title>
      Towers
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
    <ion-content>

        <ion-item collection-repeat="let tower of towers">
            <h1>Tower {{tower.name}}</h1>
        </ion-item>

    </ion-content>
</ion-content>

Then I get the following error:

Runtime Error
Error in ./TowersPage class TowersPage - caused by: Cannot read property 'name' of undefined

I think you are using ionic 2 and you need to use vitualScroll instead of collection-repeat .

<ion-list [virtualScroll]="towers">
  <ion-item *virtualItem="let tower">
    {{ tower.name }}
  </ion-item>
</ion-list>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM