Tips for adding a loading spinner using an Angular (5) ng-template?

I have a checkout page where the user must log in before proceeding. The user may already be logged in. In both cases, I want to display a spinner while the component checks if the user is logged in or not.

The code in check-out.html appears as follows:

<div *ngIf="showSpinner">
    <app-spinner></app-spinner>
</div>

<div *ngIf="auth.user | async; then authenticated else guest">
    <!-- template will replace this div -->
</div>

<!-- User NOT logged in -->
<ng-template #guest>
    <div *ngIf="auth.user == null" class="call-to-action">
        login buttons...
    </div>
</ng-template>

<!-- User logged in -->
<ng-template #authenticated>
    payment steps
</ng-template>

My check-out-component looks like this:

export class CheckoutComponent implements OnInit {
  private showSpinner = true;

  constructor(public auth: AuthService,
              private router: Router) {
              }

  ngOnInit() {
    this.auth.user.subscribe(user => {
      this.showSpinner = false;
    });
  }
...

Currently, the spinner is always displayed, but I would like to only load the spinner first and then either #guest or #authenticated. How can I achieve this?

I have done some research but have found that ngIf can only handle if-else conditions.

Answer №1

When implementing a spinner, there are three main elements involved:

A service

export enum loaderCommand { "Begin","End" };

export class LoaderService {
  private loaderSource = new Subject<any>();
  loaderEvent = this.loaderSource.asObservable();

  sendEvent(value: loaderCommand,message?:string) {
    this.loaderSource.next({command:value,message:message});
  }
}

A component for loading

export class LoadingComponent implements OnInit, OnDestroy {

  private isAlive: boolean = true;
  constructor(private loaderService: LoaderService ) { }

  ngOnInit() {
    this.dbsService.dbsEvent.pipe(takeWhile(() => this.isAlive)).subscribe((res: any) => {
      if (res.command == loaderCommand.Begin) {
        this.message = res.message ? res.message : "Loading...";
        //do something to display the spinner
      }
      if (res.command == loaderCommand.End)
        //do something to hide the spinner
    })
  }
  ngOnDestroy() {
    this.isAlive = false;
  }
}

A component, service, or interceptor that needs to show/hide the loading indicator

constructor(private loaderService: LoaderService ) { }
// To show the spinner
this.loaderService.sendEvent(loaderCommand.Begin,"Hello world");
// To hide the spinner
this.loaderService.sendEvent(loaderCommand.End);

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

Angular processes arrays as objects and fails to render the data within them

// This code has been updated during the discussion I am attempting to retrieve JSON objects (Tasks) through an HTTP request and then parse them into my own class in order to display them on my HTML page (Task Overview). Here is what I have obtained: ht ...

Utilizing *ngfor in Angular 7 to Group and Display Data

I currently have incoming data structured like this in my Angular application Visit this link to see the data format https://i.stack.imgur.com/jgEIw.png What is the best way to group and sort the data by State and County, and present it in a table as sh ...

Waiting for completion of two observables in RxJS/Angular 11 while also managing errors

Currently, I am facing the challenge of waiting for two requests to complete (observables) and performing certain actions. Here is what I need: Wait for both requests (observables) to finish If one of them fails - show one error message If both of them f ...

Tips on launching a bootstrap modal by clicking a button in an Angular project

I'm working with a Bootstrap Modal that includes a button to trigger it. Here is the code: <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data- ...

Angular to ExpressJS Backend Communication Leads to Unexpected Body Formatting Issues

For the purpose of learning Angular as a frontend and using Express as the backend, I am working on a simple todo list application. The database is managed with Sequelize. When attempting to add a user by posting to the node backend, the resulting object f ...

The styles defined in the scss file only affect the parent element and not its children

I seem to be facing a challenge related to Angular Material Chips, but I am unable to determine the exact cause or solution. Even though my specific goal differs, let me provide an example: The mat-chip-row element receives styling as shown here: https://i ...

TypeScript: custom signatures for events in a subclass of EventEmitter

Within my programming project, I have a foundational class called EventEmitter, equipped with the on method for attaching handlers to specific events: class EventEmitter { on(event: string, handler: Function) { /* internally add new handler */ ...

Unable to fetch Angular signal from service

I have been working on utilizing a service in order to store the selected division object and then access it in the detail form. Here is the code snippet for the service: private currentDivision = signal<Division>(new Division(), undefined); setC ...

Strategies for resolving the TypeScript 'possibly null' issue in ternary situations

Looking to enhance my code with a ternary operator for adding a class: className={clsx(classes.text, { classes.textSmall]: children.length > 11, })} Although this approach works, a TypeScript error is triggered: Object is possibly 'null' ...

No errors are being displayed with the React Hook Form using Zod and Material UI

Presenting my custom ProductInfoForm built using Material UI, react-hook-form with zod validations. However, I am encountering an issue: upon submitting the form, the data is displayed in the console as expected, but when intentionally triggering an error, ...

Using ng2-file-upload to upload files to Cloudinary

I am currently facing an issue with uploading images to Cloudinary using ng2-file-upload. Despite setting the endpoint in the URL and being able to see the upload in progress, I am receiving a 401 UnAuthorized error. I am looking for examples that utilize ...

Is there a way to adjust the card quantity in a Bootstrap row using media queries?

<div class="col-xl-3 col-lg-4 col-md-6 col-sm-12" *ngFor="let card of cards"> This specific div is responsible for containing the various cards that are visible on the webpage. Depending on the screen size, a different number of ...

Hiding or showing a div in an Angular 6 component using a service-triggered function

After creating a service with a method that performs an action, the next step is to have this service interact with a specific component. service.ts: doSomething() { // Carries out a task here } In this case, the target component is described below: ...

Ways to initiate an HTTP request within switchMap upon emission of a BehaviorSubject value

As I delve into writing angular applications in a declarative style, I find myself pondering on the most effective approach for handling POST requests. Specifically, I am facing a dilemma with regards to calling these requests when dealing with a login for ...

Data exchange between components via an API

I'm in the process of developing a website dedicated to showcasing the top 20 highest-rated Sci-fi movies. The main component on the homepage utilizes a GET request through a service to retrieve an array of objects containing the movie data. This movi ...

I'm struggling to figure out how to specify the data type for storing an array of objects in a variable using React.useState

I am currently working on extracting values from an .xlsx file using the SheetJS library. Below, I will provide the code snippets, errors encountered, and the different approaches I have attempted. Data extracted from var dataToJson: (6) [{…}, {…}, { ...

Selenium Intern issue: ERROR - suiteEnd message received for session that does not exist

I have been attempting to set up functional testing using Intern 4 with a headless Chrome browser. I have installed selenium-server-standalone on my Mac terminal and believe everything is configured correctly. However, when I try to run the test, I encount ...

How can one utilize withFetch() without relying on a standalone application?

After updating to angular 17.1, I encountered an error while running the app that mentioned using fetch with httpClient for SSR. NG02801: Angular detected that `HttpClient` is not configured to use `fetch` APIs. It's strongly recommended to enable `fe ...

Strategies for pausing loader/spinner animation until all HTTP responses are fully processed in Angular

Implementing a loaderInterceptor to handle spinner display and hiding functionality for multiple HTTP calls on a page. Issue: Experiencing flickering behavior in the spinner between consecutive HTTP calls. I need a solution to only display the spinner wh ...

Angular has surpassed the maximum call stack size, resulting in a Range Error

I am facing an issue while trying to include machine detail and a button bar in my app. Interestingly, this setup has worked perfectly fine in other parts of the application but is causing errors in the core module. Here is the error message main.ts impo ...