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.