- 创建Angular管道:
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'dateFilter'
})
export class DateFilterPipe implements PipeTransform {
transform(value: any[], timeInterval: string): any[] {
if (!value ||!timeInterval) {
return value;
}
const today = new Date();
let daysToSubtract = 0;
if (timeInterval === '过去7天') {
daysToSubtract = 7;
} else if (timeInterval === '过去30天') {
daysToSubtract = 30;
}
const targetDate = new Date(today);
targetDate.setDate(today.getDate() - daysToSubtract);
const datePipe = new DatePipe('en - US');
return value.filter((obj) => {
const objDate = new Date(obj.date);
return objDate >= targetDate;
});
}
}
- 在组件模板中使用管道:
import { Component } from '@angular/core';
@Component({
selector: 'app - my - component',
templateUrl: './my - component.html',
styleUrls: ['./my - component.css']
})
export class MyComponent {
data = [
{ date: '2024 - 10 - 01', name: 'Item1' },
{ date: '2024 - 10 - 10', name: 'Item2' },
{ date: '2024 - 10 - 20', name: 'Item3' }
];
}
- 在组件的模板
my - component.html
中使用管道:
<ul>
<li *ngFor="let item of data | dateFilter: '过去7天'">
{{item.name}} - {{item.date}}
</li>
</ul>
- 在模块中声明管道:
- 在相关的
NgModule
(通常是app.module.ts
)中声明管道:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform - browser';
import { DateFilterPipe } from './date - filter.pipe';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
DateFilterPipe
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}