1

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.

4
  • Where does inspections data come from? Where, when, how often do you want to transform? Commented Sep 12, 2016 at 9:52
  • It comes from an http service, so it's not changed often. I want to regroup the inspections list everytime it changes, and preferably in the component logic. Commented Sep 12, 2016 at 9:57
  • I don't think a pipe is a good idea here. What's the problem with the observable approach? Commented Sep 12, 2016 at 9:58
  • Well, basically just that inspections is not an observable. Would the input then have the type Observable<Inspection[]> and then I need to change the parent component to handle an observable instead of a regular array? It seems a little convoluted, I'd like it better if the InspectionComponent could just take a regular list and group it. Commented Sep 12, 2016 at 10:02

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That seems great, but I do need to group when items are added/removed. I suppose I want to regroup everytime angular redraws.
"I want to regroup everytime angular redraws." that sounds expensive. If you don't need to group when items are added/removed, then the approach in my answer is probably the best fit.
Well, I don't really need to regroup whenever angular redraws, but I just need any changes in the inspections list to be reflected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.