Angular ngFor index - 如何获得当前最后的偶数和奇数索引?

307 阅读1分钟

s

我们来创建一个雇员模型

export class Employee {
  id: Number;
  name: string;
  salary: Number;
}

Angular ngFor Index的语法和例子

*ngFor是ngForOf指令的简称,它可以用来遍历一个数组或对象。

下面是ngFor的语法

<div *ngFor="let object of objectarray; let i=index;">
{{i}}/{{users.length}}. {{user}} <span*ngIf="isFirst">default</span>
</div>

这可以应用于任何html元素 objectarray - 对象的数组 object - typescript对象或模型类 我们可以使用不同的局部变量

  • index 对象数组:获取数组中当前项目的索引
  • count - 数组的长度,等于array.length
  • first:如果当前对象是第一个对象,则返回真,否则返回假。
  • last返回值:如果当前对象是最后一个对象,则返回true,否则返回false。
  • even:如果当前对象的索引是偶数,则返回true。
  • odd :如果当前对象的索引是奇数,则返回真。

如何获得一个对象数组的第一个最后一个事件的奇数索引

让我们创建一个angular组件

  • 用雇员数据初始化一个对象数组
import { Component } from '@angular/core';
import { Employee } from './employee';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  employees: Employee[] = [
    { id: 1, name: 'Ram', salary: 5000 },
    { id: 2, name: 'John', salary: 1000 },
    { id: 3, name: 'Franc', salary: 3000 },
    { id: 4, name: 'Andrew ', salary: 8000 }
  ];
  constructor() {
  }

  ngOnInit() {}
}

ngFor是用来迭代一个可迭代的对象,如对象数组。

<table style="width:100%">
  <tr>
    <th>name</th>
    <th>index</th>
    <th>Count</th>
    <th>First</th>
    <th>Last</th>
    <th>Odd</th>
    <th>Even</th>
  </tr>
  <tr
    *ngFor="let employee of employees; let i=index;let count=count;let first=first;let last=last;let even=even;let odd=odd;"
  >
    <td>{{employee.name}}</td>
    <td>{{i}}</td>
    <td>{{count}}</td>
    <td>{{first}}</td>
    <td>{{last}}</td>
    <td>{{even}}</td>
    <td>{{odd}}</td>
  </tr>
</table>

输出: Angular ngfor index current example

结论

ngFor指令用来迭代一个对象数组,可以得到当前的索引,因为井检查当前的索引是first,last,oddevent