Trigger a table refresh to display updated information

When I select the select option to make an API call for a new datasource, my table appears before fetching data and it remains empty. Additionally, if I choose another select option, it displays the previous data from the previous selection.

I have attempted implementing triggers, awaits, and promises to resolve this issue.

ngOnInit() {
        getAllRoutes();
        this.currentRouteControl.valueChanges
          .pipe(takeUntil(this._unsubscribe))
          .subscribe((val: Route) => {
             this.commonCatalogueService.getRouteScheduleByRouteId(val.id)
                .subscribe((data:any) => this.dataSource = data)});
        }
    

I expect the table to render ONLY after the data has been successfully fetched. UPD: The items in the select list will be fetched in ngOnInit and added to an array. This array will then be populated into the select options using ngFor directive

<select class="m-r-20" [formControl]="currentRouteControl">
              <option *ngFor="let route of (routes$ | async)" [ngValue]="route.route">{{
                route.route.number
                }}</option>
            </select>

    private routesSubject: BehaviorSubject<RouteWrapper[]> = new BehaviorSubject(null);
    routes$ = this.routesSubject.asObservable();

    getAllRoutes() {
        this.isLoadingResults = true;
        this.commonCatalogueService
          .getRouteWrappers()
          .pipe(takeUntil(this._unsubscribe))
          .subscribe(val => {
            this.routesSubject.next(val);
            this.isLoadingResults = false;
          });
      }

    

Answer №1

To manage the rendering of a template in Angular, you can utilize NgIf, which will display a template only if the specified expression is true.

<table *ngIf="dataSource"></table>

Now, the table shown above will only appear on the page when the variable dataSource contains a value, as Javascript considers undefined to be a falsy value.

Answer №2

After importing ChangeDetectorRef, I made sure to update the displayed information as soon as the data was fetched by adding it after assigning subscription data.

import { ChangeDetectorRef } from '@angular/core';
constructor( private cd: ChangeDetectorRef ){}

this.commonCatalogueService.getRouteScheduleByRouteId(id)
            .subscribe((data:any) => {
                                      this.dataSource = data;
                                      this.cd.detectChanges();
                                      });

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

Sending data from an element within an ngFor loop to a service module

In my component, I have a loop that goes through an array of different areas with unique IDs. When you click the button, it triggers a dialog containing an iframe. This iframe listens for an event and retrieves data as JSON, then sends it via POST to an IN ...

Obtaining the dimensions of each individual child component within an NgTemplate

I have the following code snippet within my template. While I can iterate through its components using `get`, it does not return an object that allows me to access deeper into the HTML attributes. <ng-template #container></ng-template> Compon ...

Angular2 allows for the firing of all columns in one click using *ngFor

<tr *ngFor = 'let student of students> <td contenteditable="true" class ='phone' #button> {{student.phone}} <i (click)='showbox()' class = ' glyphicon glyphicon-edit'></i> <input *ngIf=&apo ...

Searching through all values can be done by following these steps

Need help with implementing a search feature that can search all values in Angular2. Here's the current code snippet: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterPipe implem ...

Troubleshooting issue with jest expect.any() failing to work with a custom class following migration from JavaScript to TypeScript

I recently made the switch to TypeScript in my project, and now some of my Jest tests are failing. It appears that the next function below is no longer being called with an AppError object, but with an Error object instead. Previously, the assertion expec ...

Step-by-step guide for deploying an Angular 2 CLI app on GitHub

As a front-end engineer, I have limited experience with deployment. Currently, I am working on my pet project using angular-cli. What is the best way to deploy it on GitHub Pages? Are there any other straightforward methods for deployment? ...

Guide on associating user IDs with user objects

I am currently working on adding a "pin this profile" functionality to my website. I have successfully gathered an array of user IDs for the profiles I want to pin, but I am facing difficulties with pushing these IDs to the top of the list of profiles. My ...

Perfroming unit testing on base class using Jasmine and Angular framework

I have a common base class that I include in every grid component. Currently, I have the specifications for the grid component, but I want to create separate specifications for the base class in its own spec file. The goal is to eliminate redundant code ...

Checkbox in Angular FormGroup not triggering touched state

There seems to be an issue with the Angular form when checking if the form is touched, especially in relation to a checkbox element. Despite the value of the checkbox changing on click, I am seeing !newDeviceGroup.touched = true. I'm not quite sure wh ...

Encountering a problem when launching the "vite-express" template on the Remix app (TSConfckParseError: error resolving "extends")

I recently launched a brand-new [email protected] project using the remix-run/remix/templates/vite-express template after executing this command: npx create-remix@latest --template remix-run/remix/templates/vite-express However, upon trying to run th ...

Is ngForIn a valid directive in Angular 4?

While attempting to loop over the properties of an object using *ngFor with in, I encountered a challenge. Here is a sample code snippet: @Controller({ selector: 'sample-controller', template: ` <ul> <li *ngFor="let i in o ...

With TypeScript, you have the flexibility to specify any data type in the generic types when using the axios.get method

axios.get('/api') When working with TypeScript as shown above, it is important to designate types for better clarity. This allows us to reference the type definition of axios, like so: (method) AxiosInstance.get<any, AxiosResponse<any> ...

Struggling to fetch information with Angular HttpClient from an API that sends back a JSON response with an array

As a beginner in Ionic and Angular, I am attempting to call an API and then showcase the team names within the template of my project. Despite following numerous tutorials and videos, I seem to be stuck as the JSON response returns an object with results f ...

Leverage the capabilities of mat-datepicker independently without relying on an

Is it possible to have the datepicker located in a fixed sidebar that is always visible and not linked to an input field? My idea was to include the component and set opened = true so that the datepicker remains in a box that is constantly displayed. ...

Guide on uploading an image to Azure Blob Storage using v10 SDK

Currently, I am attempting to upload an image to the Blob Storage in Microsoft Azure using SDK V10 within an Angular framework. The code snippet below demonstrates how I establish a connection to the Storage and retrieve the names of all containers: // E ...

The issue with loading scripts in a ReactJS NextJS app is related to the inline condition not working

I'm having trouble with an inline condition for loading scripts. The condition seems to be working because the tag is displaying text, but when it comes to scripts, it doesn't work. How can I resolve this issue? const cookie = new Cookies().get ...

Issue encountered: `property does not exist on type` despite its existence in reality

Encountering an issue in the build process on Vercel with product being passed into CartItem.tsx, despite being declared in types.tsx. The error message reads: Type error: Property 'imageUrl' does not exist on type 'Product'. 43 | ...

What is the best way to initiate a refetch when the need arises to follow a different path?

I have encountered a situation where I am able to pass the refetch function on a child component. However, an issue arises when transitioning to another page and implementing redux. This is particularly problematic when attempting to open a dialog for a ne ...

What is the reason for the function to return 'undefined' when the variable already holds the accurate result?

I have created a function that aims to calculate the digital root of a given number. Despite my efforts, I am encountering an issue where this function consistently returns undefined, even though the variable does hold the correct result. Can you help me ...

Convert the Angular PrimeNG class into a TreeNode object to avoid the error of trying to access the map property of an

Currently, I am working on a project that was created with JHipster and utilizes Angular 4.3. I want to incorporate the tree component from PrimeNG into this application. My aim is to transform an array of objects into an array of TreeNodes so that it can ...