altschuler
altschuler

Reputation: 3922

Angular 2 transform component input

I have a component like

export class InspectionComponent {    
    @Input()
    inspections: Inspections[];
}

I'd like to group the inspections by a date property. Do I use or pipe or is there a way to transform the list in the component? I'm thinking an observable, but I can't figure out if it's possible to observe a component input?

Basically what I'd like to write is something like (I know this doesn't make sense, but it shows the point)

export class InspectionComponent implement OnInit {    
    @Input()
    inspections: Inspection[];

    groups: { date: Date, inspections: Inspection[] };

    ngOnInit() {
        inspections.groupBy(...).subscribe(groups => this.groups = groups);
    }
}

I've read on the Angular Docs on Pipes that it is strongly recommended to do filtering and sorting in the component logic.

Upvotes: 1

Views: 1631

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658047

You can make inspections a setter, this way, every time when inspections are updated, grouping is executed:

groupedInspections: Inspections[]
@Input()
set inspections(inspections: Inspection[]) {
  this.groupedInspections = ...
}

In the view you bind then to groupedInspections.

You should be aware that this is not called when items are added/removed to the passed array.

Upvotes: 4

Related Questions