How to implement a filter? Angular7

57 views
Skip to first unread message

JB_0701

unread,
Dec 6, 2018, 9:32:17 AM12/6/18
to Angular and AngularJS discussion
Hello. I'm trying to implement a filter on my matTable with a DataSource(cdk). Now the filter from the Material Example doesn't work since it's not a MatDataSource and after a long search, I'm still not sure of a good way to implement it and the different components that would play a part. I found some examples using pipes (though the official material says it's rather inefficient) and creating a reference for another component of already filtered data (however, I couldn't quite grasp this concept). Could someone explain me an efficient way of implementing a filter and the components with their different functions?

Sander Elias

unread,
Dec 13, 2018, 2:17:20 AM12/13/18
to Angular and AngularJS discussion
Hi Jb,

I usually take care of filtering outside of my tables. I created a small sample for you. You can check out the repo and play with it.
The gist of it is this:

nameFilter = new FormControl('');

filter$ = this.nameFilter.valueChanges.pipe(
debounceTime(500),
distinctUntilChanged(),
startWith(''),
map((name: string) => name.trim().toLocaleLowerCase())
);

users$ = this.us.userCards$;

vm$ = combineLatest([this.users$, this.filter$]).pipe(
map(([users, filterStr]: Vm) => ({
users: users.filter(row =>
filterStr ? row.name.toLocaleLowerCase().includes(filterStr) : true
)
}))
);

I'm using a ViewModel to get my updated data into the view. 
Play with the sample, and if you have any questions don't hesitate to ask.

Regards
Sander


Johanna Berte

unread,
Dec 19, 2018, 4:54:24 AM12/19/18
to ang...@googlegroups.com
This is awesome! Thank you!

--
You received this message because you are subscribed to a topic in the Google Groups "Angular and AngularJS discussion" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/7i9_3CIlWCA/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages