In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
这篇文章主要介绍"Angular中如何使用好NgForOf的trackBy",在日常操作中,相信很多人在Angular中如何使用好NgForOf的trackBy问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"Angular中如何使用好NgForOf的trackBy"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
要想自定义默认的跟踪算法,NgForOf支持trackBy选项。trackBy接受一个带两个参数(index和item)的函数。 如果给出了trackBy,Angular 就会使用该函数的返回值来跟踪变化。
来个例子:
假设有这样的一个html
添加
{{i.id}} / {{ i.name }}
2. 然后来点ts
arr = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
{ id: 4, name: 'e' }
];
trackFunc = (index, item) => {
// 改变这里查看页面dom刷新状况
return index;
// return 'xxx';
// return item.id;
// return item.name;
};
add() {
const last = this.arr[this.arr.length - 1];
this.arr.unshift({
id: last.id, // 新加的元素id与开始定义的最后一个元素id相同,请注意!
name: Math.random().toString() // 新加的元素name是随机字符
});
}
3. 运行
以不停的往数组开始插入元素,查看页面刷新的情况。
(1)return index;
刷新全部li
(2)return item.id;
只会刷新id相同的li
(3)return item.name;
只会刷新name变化的li
(4)return 'xxx'; 纯粹搞事情。。。
情况跟return index一样,刷新全部的li
通过以上的实践可知:
(1)return index: 数组索引变化触发刷新。
(2)return item.id: 最后个元素Id与新增的元素id相同,但也在刷新;但id为1,2,3的元素,从未刷新;再以追加的方式添加元素时,id为4的未在刷新。
(3)return item.name: name属性变化触发了刷新。
(4)return 'xxx': 返回与index和item都不相关的固定值,也会触发全部刷新。
到此,关于"Angular中如何使用好NgForOf的trackBy"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.