angular2 – 如何使用轨道内部ngFor角度2
发布时间:2020-12-17 08:25:08 所属栏目:安全 来源:网络整理
导读:尝试每个语法,我可以猜测,不能使其工作! !--- 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 p
尝试每个语法,我可以猜测,不能使其工作!
<!--- 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){ 和 <ion-card *ngFor="#post of posts;trackBy:identify"> </ion-card> 这是唯一的办法吗?我不能只为trackBy指定适当的内联?
正如@Eric评论中所指出的,经过大量的阅读和玩耍,这里是如何在angular2中使用trackBy
>你需要知道它与angular1不同的语法的第一件事情,现在你需要将它与for循环分开。 用法1:跟踪对象的属性 <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; 所以 *ngFor="#post of posts;trackBy:post?.id" 与角度1相同 ng-repeat="post in posts track by post.id" 用法2:跟踪使用您自己的功能 @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}; }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |