HTML:
Name | Age |
---|---|
{{ person.name }} | {{ person.age }} |
Component:
import { Component } from '@angular/core'; import { Sort } from './sort.pipe';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [ Sort ] }) export class AppComponent { people = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 20 } ];
sortBy = 'name'; sortDirection = false;
sort(column) { if (this.sortBy === column) { this.sortDirection = !this.sortDirection; } else { this.sortBy = column; this.sortDirection = false; } } }
在该示例中,我们在组件中引入了名为Sort的管道,并在该组件的提供程序中进行了注册。我们使用管道来对存储在组件中的people数组的数据进行排序,同时也将排序器应用于ngFor指令的绑定数据。 sort函数按点击的列名称更改sortBy和sortDirection的值。在我们的HTML表格中,我们只需使用sort管道来呈现排序后的人员列表,并通过点击表头列名来应用排序器。