带组件变量的角 2 管/过滤器

Angular 2 pipe/filter with component variable

本文关键字:过滤器 组件 变量      更新时间:2023-09-26

我有显示本周和下周事件的应用程序。周通过两个按钮切换。我需要过滤器/管道,它只会显示当前活动周的事件。我在 Angular 1 中有这个过滤器,一切正常,但在 2 中我无法让这个过滤器工作。请参阅代码:

    @Page({
    templateUrl: 'build/pages/lunches/lunches.html',
    providers: [LunchService, HTTP_PROVIDERS],
})
export class Lunches {
    weekDuration:number = 24 * 60 * 60 * 7 * 1000;
    timestampFix:number = 24 * 60 * 60 * 4 * 1000;
    currentWeekNumber:number = parseInt(new Date().getTime() / this.weekDuration);
    nextWeekNumber:number = this.currentWeekNumber + 1;
    activeWeekNumber:string = '2408';
    lunches:Array;
    activeLunches:Array;
    noData:boolean = true;
    constructor(private lunchService:LunchService) {
    }
    ngOnInit() {
        this.loadLunches();
    }
    loadLunches() {
        this.lunchService.getLunchList().subscribe(
            data => {
                var lunches = data;
                lunches.forEach((item, index) => {
                    lunches[index].date = new Date(item.date);
                });
                this.lunches = lunches;
                this.weekFilter();
            }
        );
    }
    weekFilter() {
        var activeLunches = [];
        this.lunches.forEach((item, index) => {
            var lunchDate = new Date(item.date).getTime() - this.timestampFix;
            console.log(this.currentWeekNumber, ' = ', parseInt(lunchDate / this.weekDuration));
            if (this.activeWeekNumber == parseInt(lunchDate / this.weekDuration)) {
                this.noData = false;
                activeLunches.push(item);
            }
        });
        this.activeLunches = activeLunches;
    }
}

模板:

<div padding>
    <ion-segment [(ngModel)]="activeWeekNumber" (click)="weekFilter()">
        <ion-segment-button value="{{currentWeekNumber}}" selected>
            This week
        </ion-segment-button>
        <ion-segment-button value="{{nextWeekNumber}}">
            Next
        </ion-segment-button>
    </ion-segment>
</div>
<ion-card *ngIf="noData">
    <ion-card-content>
        No lunches for this week.
    </ion-card-content>
</ion-card>
<ion-card *ngFor="#lunch of activeLunches">
    <ion-card-header>
        <h2>{{lunch.date | date: "E d. M."}}</h2>
    </ion-card-header>
</ion-card>

这是我的实际代码,效果不佳,我认为它的解决方案很糟糕。我尝试将其编写为管道,但我无法访问和更改变量 noData。

编辑:根据评论,我决定使用此解决方案,但是每次活动周变量更改时如何触发周过滤器函数存在问题。有什么想法吗?

在以下情况下收到通知

activeWeekNumber:string = '2408';

变化有不同的方式。

  • 您可以将字段更改为吸气手/二传手
_activeWeekNumber:string = '2408';
get activeWeekNumber():string {
  return this._activeWeekNumber;
}
set activeWeekNumber(value:string) {
  this._activeWeekNumber = value;
}
  • 或使用 ngModel 中的事件
<ion-segment [(ngModel)]="activeWeekNumber" (ngModelChange)="doSomething($event) (click)="weekFilter()"