As I work on incorporating a search field with async
in Angular 5, I want the loading indicator to appear when the user starts typing in the search box and disappear once the results are fetched. However, following this approach led to the loading indicator being visible even without any user input. What would be the ideal way to achieve this functionality?
This is what my template looks like:
<mdl-textfield #searchBox (keyup)="search(searchBox.value)" type="text" placeholder="Search for courses, mentors, study groups..."></mdl-textfield>
<!--[...]-->
<div *ngIf="courses$ | async as courses">
<ng-container *ngIf="courses.length; else noItems">
<app-course *ngFor="let course of courses" [course]="course" [addable]="true"></app-course>
</ng-container>
<ng-template #noItems><em>No results found for "{{searchBox.value}}"</em></ng-template>
</div>
Here is the component code:
public courses$: Observable<Course[]>;
public searchCourseTerm = new Subject<string>();
public searchLoadingIndicator: boolean = false;
constructor(private courseService: CourseService) { }
ngOnInit() {
this.courses$ = this.searchCourseTerm.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((term: string) => this.courseService.searchCourses(term)),
);
}
search(term: string ){
this.searchCourseTerm.next(term);
}