0

I'm trying to implement multiple checkbox filtering using Angular but can't seem to be able to figure out how to proceed exactly. I've looked over multiple similar questions here, but failed to figure out how to use any of the answers.

Ideally, I'd like to filter my data using event listeners.

My main two issues are:

  1. Figuring out how to actually filter things, I can't figure out what the right approach would be for my goal
  2. Actually displaying updated data

Stackblitz

Any push in the right direction would be greatly appreciated!

  • Did you had a look at [this answer](https://stackoverflow.com/questions/54695113/multi-condition-filtering-with-checkboxes-javascript), you retrieve once the data then make filtered copy you pass to your component – JSmith Aug 22 '21 at 09:57
  • You're asking a lot of questions in one question, which is not suitable for SO. Try https://www.reddit.com/r/learnprogramming/ or https://www.reddit.com/r/Angular2/ – Jahir Aug 22 '21 at 10:31

1 Answers1

0

Basically, you need to share the data(filters) between two components because filtered-users and filters are two components in your project.

so, to share data between two components (which are not having parent-child relationship) we can use observables.

You can create a service called FilterService and in that, you can have an observable (filters)

@Injectable()
export class FilterService {
     private filters = new Subject<{}>(); // creating a subject

     filters$ = this.filters.asObservable(); // creating an observable

     alertFilter(key: string, value: string) {
         this.filters.next({ key, value }); // publishing the new fliter to the subscribers
     }
}

and add this service to filtered-users, filters components through dependency-injection. and call this alertFilter() method of FilterService from filters component whenever the user checks the filter checkbox.

in filter.component.html

<input (change)="onCheck('gender', opt)"

in filter.component.ts

onCheck(key: string, value: string) {
   this.filterService.alertFilter(key, value);
}

after this, subscribe to the observable(filters) of FilterService in filtered-users-component.

in filtered-users.component.ts

constructor(
  private sortingService: SortingService,
  private userService: UserService,
  private filterService: FilterService
) {
     this.filterService.filters$.subscribe({
        next: filter => {
               this.filteredUsers = this.filteredUsers.filter(user => {
                    return user[filter['key']] === filter['value'];
               });
        }
     });
}

this.filterService.filters$.subscribe() will execute whenever a new filter has been added so, using filter variable you can filter the users accordingly.

Mahesh
  • 355
  • 1
  • 12