Utilizing Angular 5: Display a Loading Indicator while Searching using Async Pipe

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);
}

Answer №1

initializeComponent() {
  this.subject$ = this.searchSubjectTerm.pipe(
    debounceTime(300),
    distinctUntilChanged(),
    tap(() => this.filtering = true)
    switchMap((term: string) => this.service.searchSubjects(term)),
    tap(() => this.filtering = false)
  );
}

This method should get the job done.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to assign Angular 2 service data to a variable within the constructor

I am facing an issue in my Angular 2 application where I need to assign the data returned from a service function to a public variable and display it in the HTML view. While the console log shows that the data is successfully fetched, it does not seem to b ...

The function in Angular 5/Typescript disappears when attempting to call it from within another function

After importing D3 into my component, I encounter an issue when trying to assign a layout to the D3.layout property. Strangely, although the layout property is present in the console output of my D3 object, it seems to be unknown when I attempt to call i ...

What is the method for retrieving array values from an attribute?

I am currently developing an Angular 6 application and I need to pass and retrieve array values dynamically through attributes. Here is the code snippet I have used for this purpose: HTML: <ul class="list-unstyled" id="list" [attr.parent_id]="123"> ...

`How can I enhance the appearance of an Angular 4 component using an attribute?`

There is a component where I need to pass specific data to the child components within an ngFor loop using attributes. Depending on the attribute, I want to style these child components accordingly. Code testimonials.component.html - (Parent component) ...

Tips for effectively utilizing the drag and drop feature with the Table Component in Ant Design

Recently, I received a new project from another team, and my client is requesting some changes to the admin page. Specifically, they want to customize the order of data pulled from the database. For instance, they would like to arrange the job positions in ...

How do I modify a response within a subscribe in Angular?

Having a scenario where multiple components are utilizing a function that expects an array of objects to be returned. However, there is one specific case where I need to modify the array based on the return value from an observable before returning it: let ...

What is the best way to extract values from a specific table column and store them in an array using Angular?

I have a section of code containing a table in my component: expect-next-month.component.html <table id="users"> <tr> <th>Number of month</th> <th>Total checking e ...

Struggling to navigate through rows in a Material UI Table

After performing a search in my TextField, the rows appear correctly in the console. However, the table itself does not update at all. I attempted to set the result of the search to a new array, but this made my TextField read-only. Any assistance with fur ...

The parameter cannot be assigned the readonly type 'X' in this context

I encountered an issue with a third-party library where the class structure changed. Initially, it was defined as: export class Foo { field: X[]; …. } In my code, I was working with this type: print(foo.field) After updating to a new version, the c ...

Can Angular PWA service worker be updated even when the browser is closed?

In my Angular PWA application, I have implemented a feature that checks for service worker updates every 15 seconds to ensure the cached static files are still valid. If there is a new deployment, the service worker silently updates the cache and notifies ...

The function '() => Promise<T>' cannot be assigned to type 'Promise<T>'

Here is an interface I have: export interface ITreeViewItem { getChildren: Promise<ITreeViewItem[]>; ... Now, let's take a look at the implementation of it: export class MyClass implements ITreeViewItem { public async getChildren() ...

what is the process for including multiple markers on Angular Google Maps?

Recently, I utilized the @agm/core module by running npm install @agm/core. This is the snippet of code that I implemented: <agm-map [latitude]="lat" [longitude]="lng"> <agm-marker *ngFor="let data of rooms" [latitude]="data.lat_long[0].lat" [ ...

Creating an ngFor loop with an ngIf condition for true and false bot conditions

I am attempting to troubleshoot an issue where if my condition is true, return true. If my condition is false, return false. However, currently, if only one condition is true, all conditions are being applied as true. Please help me resolve this problem. ...

When working with Angular 8, you may encounter an issue where the AWSIoTProvider from aws-amplify

After referencing the official link document here, I found that my code works fine with ng serve. However, after building it and trying to access the page, I encountered an error stating "AWSIoTProvider is not a constructor ". Despite searching for a sol ...

What is the best way to implement a counter with setInterval in Angular?

As a beginner in Angular, I am trying to utilize the setInterval function to count numbers, but I am facing difficulties in achieving success. Can someone provide assistance with this issue? (Apologies for any grammar mistakes in my English.) Thank you in ...

What is the best way to manually initiate an interval in rxjs?

periodicGatewaysUpdate() { return interval(GATEWAY_REFRESH_INTERVAL) .pipe( startWith(0), takeUntil(this.stopAutoRefresh), exhaustMap(() => this.fetchAllData()) ).subscribe( (gateways) => { this.gateways = gateways; ...

Exploring the capabilities of the Angular 2 expression parser alongside the functionality of the

Is there a way to create an equivalent of the Angular 1.x ngInit directive in Angular 2? I am familiar with the ngOnInit hook, which is recommended for initialization code. The ngInit directive seems like a quick and declarative way to prototype or fix a ...

Implementing an Angular function to close a window when clicking outside of it

I was browsing YouTube and came across a tutorial on how to create a directive that closes a window when clicking outside of it. However, I'm facing an issue with implementing this in my project. I built a simple to-do list application with the abilit ...

Bind the change event of an Angular input to a variable that contains a custom function

Is there a way to achieve something similar to the following? <input (input)="doSomething($event)" /> <input (input)="boolVar = $event.target.value > 5" /> I would like to accomplish it by defining a function, like this: funcVar = (e) =&g ...

Angular - tracking the window scroll event to target a specific scrollbar on a page with multiple scrollbars

I am facing difficulty in accessing a specific scrollbar from a component in my web page. The page contains multiple scrollbars, and I need to target and modify the position of a particular scrollbar (scrollTop). I have tried implementing the following co ...