angular6 *ngFor trackBy语法学习

文章参考

  1. 官网
  2. 在Angular中利用trackBy来提升性能
  3. angular中ngFor的参数

属性介绍

  1. index: number:可迭代对象中当前条目的索引。
  2. first: boolean:如果当前条目是可迭代对象中的第一个条目则为 true。
  3. last: boolean:如果当前条目是可迭代对象中的最后一个条目则为 true。
  4. even: boolean:如果当前条目在可迭代对象中的索引号为偶数则为 true。
  5. odd: boolean:如果当前条目在可迭代对象中的索引号为奇数则为 true。

trackBy来提升性能

  1. 为 *ngFor添加一个trackBy函数,告诉Angular该怎么跟踪集合的各项。
  2. trackBy函数需要两个参数,第一个是当前项的index,第二个是当前项,并返回一个唯一的标识,就像这样:

案例

模板

<ul>
	<!-- 
		1. *ngFor 实现变量的循环,里面是使用 引号 包裹
		2. 使用 let 定义变量
		3. 使用关键字  of  做循环遍历
		4. 只能使用变量i, 而不能直接使用 index作为变量使用
	-->
	<li *ngFor="let friendName of userInfoObj.friends;let i=index;
	let first=first;let last=last;odd as odd;even as even;
	trackBy: friendsTrackByIndex
	">
		<span *ngIf="first">我是第一个---{{friendName}} ---- {{index}}  ----- {{i}}</span>
		<span *ngIf="odd">我是奇数行-----{{friendName}} ---- {{index}}  ----- {{i}}</span>
		<span *ngIf="even">我是偶数行---{{friendName}} ---- {{index}}  ----- {{i}}</span>
		<span *ngIf="last">我是最后一个----{{friendName}} ---- {{index}}  ----- {{i}}</span>
	</li>
</ul>

组件中定义数据

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

// 定义一个类型
interface Student {
  name: string,
  age?: number,
  // friends: Array<any>,
  friends: any[],
  [propName: string]: any;
}

// 定义组件
@Component({
  selector: 'app-basic-page',
  templateUrl: './basic-page.component.html',
  styleUrls: ['./basic-page.component.scss']
})
export class BasicPageComponent implements OnInit {
  // 定义变量,一定要说明他是什么类型
  userInfoObj: Student;
  // 图片地址
  imgUrl: string = 'http://n.sinaimg.cn/news/1_img/dfic/3ad618a7/128/w1024h704/20190924/364c-ifaencf3678695.jpg';
  // 是否显示年龄
  isShowAge: boolean = true;

  constructor() { 
    this.userInfoObj = {
      name: 'naoteng',
      age: 18,
      friends: ['qiqi', 'yuke', 'yiming', 'siyou', 'siyu', 'junkai', 'hongyang'],
      isMarried: false
    }
  }

  getUserInfo () {
    alert(this.userInfoObj.name)
  }

  ngOnInit() {
  }

  /**
   * 
   * @param index friends变量数组的索引
   * @param item  friends 变量 循环的值
   */
  friendsTrackByIndex (index, item) {
    console.log(index, item);
    return index
  }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值