Angular does not display HTML content until the requested http data has been fully loaded

I am experiencing an issue where certain HTML content does not load until the component has received data from an API call through a service.

Below is the relevant code snippet:

import { ApiService } from './services/api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {

  thedata;

  subscription: Subscription;

  constructor(private apiService: ApiService) {}

  ngOnInit() {
    this.getData();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }


  getData() {
    this.apiService.getUsers().subscribe(
      (res) => {
        this.thedata = [res];
      },
      (err) => {
        console.log('There was an error: ' + err);
      }
    )
  }

}

Then in the HTML file:

<div *ngFor="let data of thedata">
   <!-- other elements here and below -->
    {{ data.name }}
</div>

The issue I'm facing is that the visual elements do not render until the data has finished loading. Is there a way to display the HTML content while the data is still being fetched from the API?

Answer №1

The issue at hand is the lack of data during the initialization of your component.

You can simplify the process by using the async pipe, which handles subscription and unsubscription automatically. Additionally, it ensures that the data is loaded before passing it to the loop.

Component:

import { DataService } from './services/data.service';

export interface DataModel {
  title: string;
}

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.scss']
})
export class MainComponent {

  myData: Observable<DataModel[]>;

  constructor(private dataService: DataService) {
    this.myData = this.dataService.fetchData(); // Expected return is an array of objects ///
  }
}

Template:

<div *ngFor="let item of myData | async">
   <!-- other elements go here -->
    {{ item.title }}
</div>

Answer №2

If thedata remains empty, the *ngFor loop will not execute, preventing any content within the div from being added to the DOM. To display content while data is loading, it must be placed outside of the *ngFor loop.

Answer №3

It is not possible to display the "repeater template" in the DOM when using the *ngFor directive, as it creates repeated elements based on the number of items in your array.

To work around this and simulate the presence of items before receiving the API response, you can initialize the array with dummy data in your TypeScript code like so:

thedata = [1,2,3,4,5,6]

Answer №4

Give this a shot:

.ts

 fetchData() {
const that = this;   //<====== include this line
    this.apiService.getPosts().subscribe(
      (response) => {
      console.log(JSON.stringify(response)); <======
        that.fetchedData = [response];    
      },
      (error) => {
        console.log('An error occurred: ' + error);
      }
)

}

.html

<ng-container *ngIf="fetchedData">
<div *ngFor="let item of fetchedData">
   <!-- more elements here and below -->
    {{ item?.title }}
</div>
</ng-container>

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

Showcasing an input field once a specific button is pressed in an Angular application

When triggered, I am looking for a blank panel that will display a text box within the same panel. This functionality should be implemented using Angular. ...

Why aren't the validations being set when creating Angular forms using formControl.values?

I had to structure the form in a specific way in my app.ts file -> courseNameControl = new FormControl("", [Validators.required,Validators.minLength(2)]); contentControl = new FormControl("", Validators.required); form = { cours ...

Issue with PrimeReact dropdown component not recognizing an array in TypeScript

Trying to incorporate the PrimeReact Dropdown component in a NextJs app with TypeScript. Encountering an error when attempting to select options from the dropdown list: "Objects are not valid as a React child (found: object with keys {name, code})" The b ...

Even when there is a change in value within the beforeEach hook, the original value remains unchanged and is used for dynamic tests

My current project setup: I am currently conducting dynamic tests on cypress where I receive a list of names from environment variables. The number of tests I run depends on the number of names in this list. What I aim to achieve: My main goal is to manip ...

There seems to be an issue with transitioning the React.js page

I'm currently working on managing the page with react-hook, react-router-dom, and redux. The login functionality has been implemented, and I've written the code to redirect to the main page upon successful login. To achieve this, I utilized hi ...

Unusual behavior when importing in Angular 2 using TypeScript

While working on a demo for another question on Stack Overflow, I initially used angular-cli and then switched to Plunker. I noticed a peculiar difference in behavior with the import statement between the two setups. The issue arises with the second impo ...

How to set up an Angular ErrorHandler?

Attempted to register an Angular ErrorHandler in this simplified StackBlitz environment, but it seems that it's not capturing the error thrown within the constructor of the HelloComponent. Any insights on this issue? Your opinions? ...

Verify if the property in every element of the array is not empty

How can you determine if all employees have a non-null value for the SSN property in the given object? Employees: { id: 0, name: "John", SSN: "1234" } { id: 1, name: "Mark", SSN: "1876" } { id: 2, name: "Sue&q ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

Creating an ESNext JavaScript file and integrating it into an Angular 2 project: A comprehensive guide

I am facing an issue with my js file named UserService.js and source.js, which has been transformed using transformer typescript. My objective is to integrate this transformed js file into Angular. UserService.js import { Source } from "./source" ...

Creating various styles for cards using ngFor within Angular

I have been working on applying different styles to cards created using ngFor in Angular. Here's how it currently looks: https://i.sstatic.net/UhbSp.png My aim is to set unique styles for each card. Due to the ngFor loop used in creating them, I ini ...

Coding with Angular 4 in JavaScript

Currently, I am utilizing Angular 4 within Visual Studio Code and am looking to incorporate a JavaScript function into my code. Within the home.component.html file: <html> <body> <button onclick="myFunction()">Click me</button> ...

Flux Utils identified an issue stating that the Class constructor App cannot be called without the 'new' keyword

Struggling to set up a Flux Util container for this React component: class App extends React.Component<{},AppState> { constructor(props:Readonly<{}>){ super(props); } static getStores(){ return [ArticlesStore]; } static calcul ...

Guide on toggling the button by clicking on the icon to turn it on or off

Within my angular application, I have implemented font icons alongside a toggle switch. Initially, the switch is in the ON state. The specific functionality desired is for clicking on an icon to change its color from white to red (this has been achieved) ...

Exploring Angular: How to Access HTTP Headers and Form Data from POST Request

I am currently working with an authentication system that operates as follows: Users are directed to a third-party login page Users input their credentials The website then redirects the user back to my site, including an auth token in a POST request. Is ...

How come TypeScript tuples support the array.push method?

In the TypeScript code snippet below, I have specified the role to be of Tuple type, meaning only 2 values of a specified type should be allowed in the role array. Despite this, I am still able to push a new item into the array. Why is the TS compiler not ...

Issue NG0203 encountered during material import attempt

I've been encountering an issue with importing material. Despite using code similar to the examples on material.angular.io, I keep running into the ""inject() must be called from an injection context..." error. My goal is to create a simple table ...

What is the best way to switch the direction of the arrows based on the sorting order?

Is there a way to dynamically change the direction of arrows based on sorting, similar to the example shown here? sortingPipe.ts: import { SprBitType } from '../spr-bit-type/sprBitType'; import { Pipe, PipeTransform } from '@angular/core& ...

Having trouble with React npm start: 'No chokidar version found' error occurring

After cloning my React-Typescript app on Github Pages and attempting to make some changes, I encountered an issue. Despite running npm install to install all dependencies, when I tried to run npm start, I received the following error message: https://i.st ...

Poorly packaged library - Custom Angular library - Node Package Manager

Recently, I've been delving into the process of publishing a simple Angular library on NPM. Despite following various tutorials (like those found here, here, and here), I faced difficulties when attempting to use it in a test project. MY JOURNEY In s ...