如何在ngFor中使用trackBy [英] How to use trackBy with ngFor

查看:269
本文介绍了如何在ngFor中使用trackBy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不明白我应该从trackBy返回什么.根据我在网上看到的示例,我应该返回对象上某些属性的值.这是正确的吗?为什么我将索引作为参数?

I can't really understand what I should return from trackBy. Based on examples I've seen on the web, I should return the value of some property on the object. Is it correct? Why do I get index as a parameter?

例如,在以下情况下:

constructor() {
    window.setInterval(() => this.users = [
            {name: 'user1', score: Math.random()},
            {name: 'user2', score: Math.random()}],
        1000);
}

userByName(index, user) {
    return user.name;
}

...

<div *ngFor="let user of users; trackBy:userByName">{{user.name}} -> {{user.score}}</div>

尽管名称不变,模板中显示的对象仍会更新.为什么?

The objects shown in template are still updated despite the name being unchanged. Why?

推荐答案

在为ngForOf指令触发的每个ngDoCheck上,Angular都会检查哪些对象已更改.它在此过程中使用不同的函数,并且每个函数都使用trackBy函数将当前对象与新对象进行比较.默认的trackBy函数按身份跟踪项目:

On each ngDoCheck triggered for the ngForOf directive Angular checks what objects have changed. It uses differs for this process and each differ uses trackBy function to compare the current object with the new one. The default trackBy function tracks items by identity:

const trackByIdentity = (index: number, item: any) => item;

它将接收当前项目,并应返回一些值.然后,将函数返回的值与该函数最后一次返回的值进行比较.如果值更改,则差异报告更改.因此,如果默认函数返回对象引用,则如果对象引用已更改,则它将与当前项目不匹配.因此,您可以提供自定义的trackBy函数,该函数将返回其他内容.例如,对象的某些键值.如果此键值与上一个键值匹配,则Angular将不会检测到更改.

It receives the current item and should return some value. Then the value returned by the function is compared against the value this function returned the last time. If the value changes, the differ reports a change. So if the default function returns object references, it will not match the current item if the object reference has changed. So you can provide your custom trackBy function that will return something else. For example, some key value of the object. If this key value matches the previous one, then Angular will not detect the change.

不再支持语法...trackBy:userByName.现在,您必须提供功能参考.这是基本示例:

The syntax ...trackBy:userByName is no longer supported. You must now provide a function reference. Here is the basic example:

setInterval( () => {
  this.list.length = 0;
  this.list.push({name: 'Gustavo'});
  this.list.push({name: 'Costa'});
}, 2000);

@Component({
  selector: 'my-app',
  template: `
   <li *ngFor="let item of list; trackBy:identify">{{item.name}}</li>
  `
})
export class App {
  list:[];

  identify(index, item){
     return item.name; 
  }

尽管对象引用发生了变化,但DOM并未更新. 这是油轮.如果您好奇ngFor的工作原理,请阅读此内容答案.

Although the object reference changes, the DOM is not updated. Here is the plunker. If you're curious how ngFor works under the hood, read this answer.

这篇关于如何在ngFor中使用trackBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆