MST

星途 面试题库

面试题:Angular自定义管道在复杂数据处理中的应用

假设你有一个包含多个对象的数组,每个对象都有一个日期属性。请创建一个自定义Angular管道,能够根据传入的时间间隔(如过去7天、过去30天等)过滤出符合条件的对象,并在组件模板中正确使用该管道展示过滤后的数据。
40.0万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试
  1. 创建Angular管道
    • 首先,使用Angular CLI生成管道:
      ng generate pipe dateFilter
      
    • 然后在date - filter.pipe.ts文件中编写管道逻辑:
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;
    });
  }
}
  1. 在组件模板中使用管道
    • 假设组件的ts文件中有一个包含对象的数组,如下:
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>
  1. 在模块中声明管道
    • 在相关的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 {}