Reputation: 1684
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
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
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