Issue
I have the below setup. The search input box works great. I have now added the toggle and I am trying to understand how to make both work together.
I have created a BehaviourSubject & Observable combination for the search term then am watching the observable to trigger the filtering of the object.
searchString = new BehaviorSubject("");
searchString$ = this.searchString.asObservable();
this.myForm.controls.searchString.valueChanges.pipe(
debounceTime(400),
distinctUntilChanged(),
tap((val) => this.searchString.next(val))
).subscribe()
this.searchString$.subscribe((searchTerm) => {
console.log(this.userNames);
if (this.userNames !== undefined) {
this.filteredUserNames = this.userNames.filter(
(userName) =>
userName.searchTerms
.toLowerCase()
.indexOf(searchTerm.toLowerCase()) !== -1
);
};
This works fine. Now I have the toggle set up with a formcontrolname and Valuechanges observable
this.myForm.controls.isActive.valueChanges.pipe(
tap( val => this.userIsActive = val)
).subscribe()
This toggles the userIsActive. In filteredUserNames I have a property isActive: boolean
What is the best way to filter the filteredUserNames object by both the searchTerm and the isActive state?
EDIT: The users object looks like this
{id: 52, firstName: "Administrator", lastName: "Account", employeeId: null, jobTitle: "Learning Administrator", isActive: false …}
The filteredUserNames list is used as in a *ngFor in the template.
<div (click)="selectUser(userName)"
*ngFor="let userName of filteredUserNames">
{{userName.title}}
etc...
</div
I need to filter the list with both filters isActive and SearchTerm. So if the inactive is switched to false then the search box will only search the inactive list and if it is switched to true the search box will search the whole original list.
Solution
Assuming you have an endpoint, FormGroup will return its full value
destroy$ = new Subject<any>();
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
ngOnInit() {
this.myForm.valueChanges
.pipe(
// To clear valueChanges
takeUntil(this.destroy$),
debounceTime(400),
distinctUntilChanged(),
// This will take a val and switch to an endpoint of a choice
switchMap((val) => this.onSearch(val))
).subscribe(res => { });
}
private onSearch() {
return {{ endPoint }}
};
if its a local search make switchMap back to tap and do some local filtering with an object of form value
Answered By - Dmitriy

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.