jgerstle
jgerstle

Reputation: 1684

How to get a reference to the list in an ngfor with a pipe applied to it

I am applying a filter to a list inside an ngfor like so *ngFor="data | pipe" I want access to the object that gets outputted from the filter in my ts component class. I tried using this: *ngFor="data | pipe as filtereddata", but I think that only works relative to the tag and doesn't seem to get applied to the object on the component. Is there a way to get access to this filtered data?

For reference the pipe does a sort and a filter and I want to be able to select the first item in the list and I don't want to have to resort the data in the ts if it's already being done.

Upvotes: 0

Views: 372

Answers (2)

sanju govind
sanju govind

Reputation: 1

import { TestPipe } from 'ts file location'

@Component({
selector:'YourComponent',
templateURl:'Component Html Path'
})
export class ComponentClassName implements OnInit{
private formattedData: any;
constructor(private pipe: TestPipe, private service:yourService){}
ngOnInit(){
//Service call to fetch data
this.service.getData().subscribe((data) =>{

    this.formattedData = this.pipe.transform(data); // use formattedData to bind in HTML

})
}
}

formattedData will have reference in your component file. You can apply the transform in a separate function and invoke it every time the array changes

Upvotes: 0

Nikola Yankov
Nikola Yankov

Reputation: 1304

I would suggest to put your sorting logic in a property with getter in your ts. Something like:

get sortedData(): any[] {
    return ...your sorting logic...
}

Than do the ngFor through this sortedData property.

Note: return type from the getter could be you specific type ( e.g. YourType[] )

I hope this will help you

Upvotes: 0

Related Questions