Fetch data from the api prior to rendering the view

I have a basic accordion set up:

HTML

<div *ngFor="let item of showDirNames | async | filter: name; let i = index;">
   <button class="accordion" (click)="toggleAccordion($event, i, item.name)"> {{item.name}} </button>
   <div class="panel" hide="!item.isActive">
      <p *ngFor="let child of showFilesNames | async | filter: name"> {{child.name}} </p>
   </div>
</div>

TS

    toggleAccordion(event, index, item) {
      this.activeIndex = index;
      var element = event.target;
      
      if(element.classList.toggle("active")){
        this.showFiles(item);
      }

      if(this.element[index].isActive) {
        this.element[index].isActive = false;
      } else {
        this.element[index].isActive = true;
      }
      var panel = element.nextElementSibling;
      if (panel.style.maxHeight) {
        panel.style.maxHeight = null;
      } else {
        panel.style.maxHeight = panel.scrollHeight + "px";
      }
  }

Here's how I retrieve the data

showFiles(filename: string) 
{
    this.showFilesNames = this.uploadService.getFiles(filename);
    this.showFilesNames.forEach(element => {});
}

What should the final result look like? I want to click on the header of my accordion to get the title and then send that title to my backend for filenames. The issue is that my view loads before the data is available.

Answer №1

If you use

<ng-container *ngIf="showFileNames | async as fileNames">
, it will only display the variable once it has data. Then, you can loop through using
<p *ngFor="let fileName of fileNames | filter : name>"
. This approach should help you achieve your desired outcome.

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

Issue with Angular 8 Material: mat-option remains unselected after update

When using Angular 8, I encountered an issue where the mat-option was not selecting a specific option. It worked fine when I used static options, but failed on dynamic mat-options. <mat-label>Item Category {{item.category_id}}</mat-label> & ...

Choose the checkbox by utilizing pre-populated information in Angular 6

I am looking to present a list of roles in checkboxes, where if a role has been previously selected, the checkbox should be pre-checked. Here is the code I am using to return the rolesId: this.Adu.optionId=this.selectedEdit; this.otionService.GetRolesfoO ...

A guide to implementing previousState in React hooks with TypeScript

I am trying to grasp the concept of using previous state with react hooks in typescript. The code snippet provided below does function, however, it throws an error stating: Type 'number' is not assignable to type 'HTMLDivElement'. Whi ...

The symbol 'router-outlet' is not recognized by the system

This new project utilizes Angular 13 for its implementation. One of the key updates is the addition of routing to the project, specifically in the file app-routing.module.ts. import { NgModule } from '@angular/core'; import {RouterModule, Routes ...

Angular 12 - Issue: None of the available overloads match this call. Overload 1 out of 5

Here is the code snippet I am working with: import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { BehaviorSubject } from 'rxjs'; import { HttpClient } from '@angular/common/http&ap ...

Utilizing Material-UI with MobileDialog HOC in TypeScript: A Beginner's Guide

I'm running into an issue while trying to implement withMobileDialog in my TypeScript code. Below is the snippet of my code, inspired by a code example from the official documentation. import withMobileDialog, { InjectedProps } from "@material-ui/co ...

Error: Angular 2 Missing Required Dependency - @angular/core version 2

I am a beginner in AngularJS2 and I am looking to incorporate a server-side datatable in my application. To achieve this, I have utilized the following command: npm install --save ng2-smart-table library However, when executing this, an error is encoun ...

Struggling to tally the entries and authenticate logins within Ionic 3 and Angular

In my application, users register by providing their email and password, which is then stored in a SQLite database. When the user attempts to log in using the same credentials, they should be redirected to the home page upon successful login. I am facing ...

I possess an item, but unfortunately, I am only able to save the first object from this possession

I have an object, but I can only save the first item from this object. Interface: export interface PhotoToCreate { albumName: string; albumTitle: string; ImageNameO : string; imageNameT : string; } Component import { Component, OnI ...

I am looking for unique values from a duplicate string that is separated by commas in TypeScript

Using TypeScript, I am trying to extract unique values from a list of comma-separated duplicate strings: this.Proid = this.ProductIdList.map(function (e) { return e.ProductId;}).join(','); this.Proid = "2,5,2,3,3"; The desired output is: this. ...

How to Implement Angular ngStyle with ChangeDetectionStrategy.OnPush?

Check out this StackBlitz demonstration that demonstrates how ngStyle is being used to style the h1 element in the following way: <h1 [ngStyle]="{'background-color': backgroundColor}" The component named HelloComponent employs the O ...

Leveraging Angular 4-5's HttpClient for precise typing in HTTP requests

Utilizing a helper service to simplify httpClient calls, I am eager to enforce strong typing on the Observable being returned. In my service where I utilize the api Service and attempt to obtain a strongly typed observable that emits: export class ApiU ...

What is the best way to organize a collection of objects by a specific characteristic in Typescript?

Imagine you have an array of objects with the following structure: type Obj = { id: number, created: Date, title: string } How can you effectively sort this array based on a specific property without encountering any issues in the type system? For ...

The expansion feature of PrimeNG Turbotable

I'm currently facing an issue with the Primeng Turbotable where I am unable to expand all rows by default. You can find a code example of my problem at this link. I have already tried implementing the solution provided in this example, but unfortuna ...

(NextAuth) Error: The property 'session' is not found within the existing type '{}'

While working on a NextJs project with NextAuth, I encountered the following error: "Type error: Property 'session' does not exist on type '{}'.". To resolve this issue, I added the session property to my _app.tsx file as sugg ...

The absence of color gradations in the TypeScript definition of MUI5 createTheme is worth noting

Seeking to personalize my theme colors in MUI5 using TypeScript, I am utilizing the createTheme function. This function requires a palette entry in its argument object, which TypeScript specifies should be of type PaletteOptions: https://i.stack.imgur.com ...

Struggling with implementing tree-shaking in date-fns 2

I am struggling to understand how the tree-shaking feature works in date-fns version 2... To assist me, I have created a simple project using: date-fns 2.1.0 webpack 4.39.3 typescript 3.6.2 The project consists of 2 files, one acting as the "library" a ...

Encountering a Node-gyp rebuild issue while integrating NGRX into an Angular application on Mac OS

I am currently working on integrating ngrx/store into my Angular application. Johns-MBP:Frontend johnbell$ npm install @ngrx/store <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aac9cbc4dccbd9ea9b849c849b99">[email pr ...

Encountered an error while attempting to install the 'ionic-native' package

Currently, I am navigating through this particular link to integrate local notifications into my Ionic 2 application. To kickstart the process, I executed the following two commands: Username@DESKTOP-BNKQVBC MINGW64 ~/Reminder-App (platform-specific) $ n ...

Configuring Redux Provider for Jest Testing

I'm currently working on setting up a redux provider for Jest testing in my react app. To achieve this, I believe I need to implement the following code snippet: import {ReactNode} from 'react' import {Provider} from 'react-redux' ...