尝试每个语法,我可以猜测,不能使其工作!
<!--- THIS WORKS FINE ---> <ion-card *ngFor="#post of posts"> {{post|json}} </ion-card> <!--- BLANK PAGE ---> <ion-card *ngFor="#post of posts track by post.id"> {{post|json}} </ion-card> <!--- Exception : Cannot read property 'id' of undefined ---> <ion-card *ngFor="#post of posts;trackBy:post.id"> {{post|json}} </ion-card> <!--- Exception : Cannot read property 'undefined' of undefined ---> <ion-card *ngFor="#post of posts;trackBy:posts[index].id"> {{post|json}} </ion-card> <!--- Blank page no exception raised ! ---> <ion-card *ngFor="#post of posts;#index index;trackBy:posts[index].id"> {{post|json}} </ion-card>
对我而言,唯一的做法是
>在控制器类中创建方法
识别(index,post:Post){
返回post.id
}}
和
<ion-card *ngFor="#post of posts;trackBy:identify"> </ion-card>
这是唯一的办法吗?我不能只为trackBy指定适当的内联?
正如@Eric评论中所指出的,经过大量的阅读和玩耍,这里是如何在angular2中使用trackBy
原文链接:https://www.f2er.com/angularjs/145057.html>你需要知道它与angular1不同的语法的第一件事情,现在你需要将它与for循环分开。
<ion-card *ngFor="let post of posts;trackBy:post?.id"> </ion-card> ---or--- <ion-card *ngFor="let post of posts;trackBy:trackByFn"> </ion-card>
在这里你问角2
>创建一个局部变量post;
>你告诉trackBy等待,直到这个本地变量准备好了“你这样做通过使用elvis操作符’后面的问号
变量名称“,然后使用其id作为跟踪器。
所以
*ngFor="#post of posts;trackBy:post?.id"
与角度1相同
ng-repeat="post in posts track by post.id"
@Page({ template: ` <ul> <li *ngFor="#post of posts;trackBy:identify"> {{post.data}} </li> </ul> ` }) export class HomeworkAddStudentsPage { posts:Array<{id:number,data:string}>; constructor() { this.posts = [ {id:1,data:'post with id 1'},{id:2,data:'post with id 2'} ]; } identify(index,item){ //do what ever logic you need to come up with the unique identifier of your item in loop,I will just return the object id. return post.id } }
trackBy可以使用回调名称,它会将它称为我们提供两个参数:循环的索引和当前项。
为了实现与角度1相同,我曾经做过:
<li ng-repeat="post in posts track by identify($index,post)"></li> app.controller(function($scope){ $scope.identify = function(index,item) {return item.id}; });