Creating a loading screen in Angular 4: Insert an item into the HTML and then set it to disappear automatically after

I'm dealing with a loading screen that typically takes between 15-30 seconds to load about 50 items onto the page. The loading process displays each item on the page using the message:

Loading item x

For each data call made to the database, an observable/subscription is used. When the data is received, the subscription triggers and adds it to an HTML string like this:

sync() {
    this.syncStatus = "Starting sync"
    this.syncService.sync().subscribe((status: string) => {
        this.syncStatus += "<div>" + status + '</div>';
    }, (error: string) => {
        console.log(error);
    }, () => {
        this.Redirect();
    });
}

<div class="description">
   <span [innerHTML]="syncStatus"></span>
</div>

Currently, the list display can get cut off due to its length, especially when there are more than 50 items (sometimes even hundreds). I am looking for a way to display each individual item on the page for 5 seconds before hiding it. Any suggestions?

Answer №1

To organize the sync status, you can store objects with timestamps and then sort them accordingly.

sync() {
    this.syncStatus = [{ msg: 'Starting Sync', time: Date.now() }];
    this.syncService.sync().subscribe((status: string) => {
        this.syncStatus.unshift(status);
        this.removeOldEntries();
    }, (error: string) => {
        console.log(error);
    }, () => {
        this.Redirect();
    });
}

You can remove outdated entries by filtering:

removeOldEntries() {
   this.syncStatus = this.syncStatus.filter((status) => status.time < Date.now() - 300000); // 5 minutes
}

Answer №2

Utilizing Angular components can greatly enhance your development process

Check out the Source Code on Stack Blitz

Explanation of Component Usage

  1. Avoid the need for date creation to track data arrival times
  2. Easily manage and avoid sifting through large datasets
  3. By adopting Angular component methodology, each component can autonomously handle its removal

Main Component.ts Implementation

export class AppComponent {
  data = [
    "Hello 0"
  ];

  count = 1;

  ngOnInit() {
    // Simulate backend subscription
    setInterval(() => {
      if (!this.data) {
        this.data = []
      }

      this.data.push("Hello " + this.count ++);
    }, 1000);
  }
}

Main Component.html Structure

<div class="description">
   <div *ngFor="let datum of data; let i = index">
     <hello [ref]="data" [index]="i">{{datum}}</hello>
   </div>
</div>

Hello.ts Component Logic

@Component({
  selector: 'hello',
  template: `<ng-content></ng-content>`
})
export class HelloComponent  {
  @Input() ref;
  @Input() index: number;

  ngOnInit() {
    // Automatically remove component after specified timeout
    setTimeout(() => {
      this.ref.splice(this.index, 1);
    }, 5000);
  }
}

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

Creating a concise TypeScript declaration file for an established JavaScript library

I'm interested in utilizing the neat-csv library, however, I have encountered an issue with it not having a typescript definition file available. Various blogs suggest creating a basic definition file as a starting point: declare var neatCsv: any; M ...

Trying to figure out how to execute a codeigniter helper function with JQuery AJAX?

I created a handy function in my helper file within codeigniter that formats prices based on the value and currency ID provided. if(!function_exists('format_price')){ function format_price($val,$curency_id=NULL){ $CI ...

What is the correct way to initialize and assign an observable in Angular using AngularFire2?

Currently utilizing Angular 6 along with Rxjs 6. A certain piece of code continuously throws undefined at the ListFormsComponent, until it finally displays the data once the Observable is assigned by calling the getForms() method. The execution of getForm ...

Guide on importing a client-side script using browserify with module.exports exposed through jadeify

I've successfully created a JavaScript file using a Jade template with the help of browserify, browserify-middleware, and jadeify on the server side in Node. The only thing required to generate the JavaScript file is: app.use('/templates', ...

Angular app unit tests encountering issues due to Keycloak role-based redirection mechanism

In my Angular application, I needed to redirect users to either /route1 or /route2 based on their role. However, Keycloak only allows for a single route to be specified after logging in (in this case, route1). To solve this routing dilemma, I implemented t ...

Is there a way to automatically compress Express JS assets?

Is there a way to dynamically minify the frontend JavaScript/CSS of my Express JS application? Are there any potential drawbacks to this approach? ...

Developing a tool for switching between languages in an internationalization application

I have been exploring the implementation of Lingui(i18n) in apps. All set up, but I'm interested in adding a language switcher to enable users to change between language catalogs on my app. Here's my index.js file: import React, { useEffect } fr ...

Retrieve the initial element from a JSON object to identify errors, without being dependent on its specific key name

Utilizing AngularJS, my JSON call can result in various errors. Currently, I am handling it like this: $scope.errors = object.data.form.ERRORS or $scope.errors = object.data.system.ERRORS However, in the future, 'form' or 'system' ...

JavaScript's Ajax POST request to PHP is not functioning as expected

My current code setup involves handling $_GET[] requests on the products.php page by passing them to get_data_products.php via an ajax POST request. The data retrieved from get_data_products.php is then displayed accordingly. PHP if(isset($_GET['cat ...

When attempting to dispatch in getServerSideProps, the State refuses to change. Could it be due to the Redux-Next-Wrapper?

I'm facing an issue where the Redux Store does not change when I dispatch in getServerSideProps. Even though I can see the changes in console log after dispatch, the store appears as an empty array when the page loads. Why are these changes not taking ...

Issues arise when using ng-repeat in conjunction with ng-click

I am facing some new challenges in my spa project with angularjs. This is the HTML snippet causing issues: <a ng-repeat="friend in chat.friendlist" ng-click="loadChat('{{friend.friend_username}}')" data-toggle="modal" data-target="#chat" d ...

Steps for setting up type-graphql in your projectNeed help with

Trying to include this in my TypeScript project: import { ID } from "type-graphql"; Encountered an issue when attempting to install type-graphql. Received a 404 error stating that it could not be found in the npm registry. npm install @types/type-graphq ...

Is there a way to showcase the JSON data within a nested array using VueJS?

Here is my Vue.js code: <script> new Vue({ el: '#feed' , data: { data: [], }, mounted() { this.$nextTick(function() { var self = this; var id = window.location.href.split('=').pop(); ...

Timeout error of 10000ms occurred while using await with Promise.all in Mocha unit tests

Document: index.ts // Default Exported Classes getItemsA() { return Promise.resolve({ // Simulating API call. Mocking for now. success: true, result: [{ itemA: [] }] }); } getItemsB() { return Promise.resolve({ // Simulating API cal ...

Error message shows explicit Typescript type instead of using generic type name

I am looking to use a more explicit name such as userId instead of the type number in my error message for error types. export const primaryKey: PrimaryKey = `CONSUMPTION#123a4`; // The error 'Type ""CONSUMPTION#123a4"" is not assignable to ...

TextGeometry failing to render

Currently experimenting with TextGeometry. Successfully implemented BoxGeometry, but encountering issues with TextGeometry. Experimenting with different material options like MeshNormalMeterial, however, still unable to resolve the issue var scene = new ...

MTG Life counter. Display fluctuations in count

I am currently working on a fun project creating an MTG (Magic The Gathering) life tracker, even though the code is quite messy. Despite its flaws, it still gets the job done. Click here to view the MTG life tracker https://i.stack.imgur.com/Su17J.png ...

Issue encountered when AngularJS struggles to evaluate regular expression within ng-pattern

Currently, I am implementing the ng-pattern argument in an input text field to restrict input to only numeric values: <input type="text" ng-model="numericField" ng-pattern="/^[0-9]*$/" /> However, there seems to be an unusual behavior in the regex ...

Making a single variable object as opposed to using multiple variables

In order to improve the code structure, I am looking to consolidate all properties into a JavaScript object instead of using multiple variables: // Method 1 // This method gives an error as _inp cannot be accessed by input_value // Uncaught TypeError: Can ...

Troubleshooting Problems with Linking Components to app.component.html in Angular

I have created a few components, but I am having trouble getting them to work properly. When running 'ng serve', I encounter errors. If 'app-test' is supposed to be an Angular component, make sure it is included in the '@Compone ...