Browse Source

自訂Pipe使用,使用 ng generate pipe [管道名稱]

本範例使用自訂Orderby排序
master
HarveyMac 2 years ago
parent
commit
6e9b7d075a
  1. 2
      src/app/app.component.html
  2. 13
      src/app/app.component.ts
  3. 3
      src/app/app.module.ts
  4. 14
      src/app/order-by.pipe.ts

2
src/app/app.component.html

@ -1 +1 @@
UTC時間:{{ now | date: "long":"+0800" }}
<app-task *ngFor="let task of tasks | orderBy: 'State'" [task]="task"></app-task>

13
src/app/app.component.ts

@ -1,10 +1,17 @@
import { Component } from '@angular/core';
import { Task } from './task';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
now = new Date();
export class AppComponent {
tasks: Task[] = [
new Task({ TaskSn: '001', TaskName: '待辦事項 A', State: 'Finish' }),
new Task({ TaskSn: '002', TaskName: '待辦事項 B', State: 'Doing' }),
new Task({ TaskSn: '003', TaskName: '待辦事項 C', State: 'None' }),
new Task({ TaskSn: '004', TaskName: '待辦事項 D', State: 'None' }),
];
}

3
src/app/app.module.ts

@ -4,10 +4,11 @@ import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { TaskComponent } from './task/task.component';
import { OrderByPipe } from './order-by.pipe';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, TaskComponent ],
declarations: [ AppComponent, TaskComponent, OrderByPipe ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

14
src/app/order-by.pipe.ts

@ -0,0 +1,14 @@
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
transform(list: any[], prop: string): any[] {
return list.sort((a, b) => a[prop] >b[prop]
?1
:a[prop]=== b[prop] ?0: -1)
}
}
Loading…
Cancel
Save