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

Issue: ENOENT - The requested file or directory cannot be found in the context of an Angular2 and Express.js

I have made some changes to the Angular2 app on GitHub in order to use Express.js instead of KOA. However, when I try to load the app in FireFox, I encounter the following error in the `nodemon` console: Error: ENOENT: no such file or directory The Angul ...

I recently incorporated @angular/material into my project and now I am encountering a version compatibility issue

I am currently facing a versioning challenge in my Angular project. My goal is to operate on Angular 6, but despite trying various guides on how to reversion the project, I have been unsuccessful. Here is the output of my 'ng version' command: ...

Here's a guide on using a button to toggle the display of password value in Angular, allowing users to easily hide

I have successfully implemented an Angular Directive to toggle the visibility of password fields in a form. However, I am facing an issue with updating the text displayed on the button based on the state of the input field. Is there a way for me to dynami ...

AngularJS component downgraded without change detection

Currently, I am utilizing Angular's downgradeComponent for performance optimization purposes. You can find more information about it here: https://angular.io/api/upgrade/static/downgradeComponent. The Angular component I am working with is defined as ...

One-Of-A-Kind Typescript Singleton Featuring the Execute Method

Is it feasible to create a singleton or regular instance that requires calling a specific method? For instance: logger.instance().setup({ logs: true }); OR new logger(); logger.setup({ logs: true }); If attempting to call the logger without chaining the ...

After routing, parameters are mistakenly being inserted into the URL

When working with Angular 5 and using routing to move between pages / components, I am facing an issue. Specifically, in the login component, after signing out I navigate to the Home component but unnecessary parameters are being added to the URL. Below i ...

The creation of an Outlook 365 add-in using Angular8 presents challenges when attempting to delete a cookie that was generated with ngx

I have developed an Office 365 add-in for Outlook. The add-in is built using Angular8 and I am utilizing ngx-cookie-service to store my authentication token information in a cookie. Despite being able to install the add-in, store the auth token in the co ...

Acquiring the handle of ngComponentOutlet

I am dynamically creating a component using ngComponentOutlet. Here is an example: import {Component, NgModule} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' @Component({ selector: 'alert-success& ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

Has the Angular 2 community established a standardized ecosystem?

As a developer specializing in Angular 1, I am now eager to dive into the world of Angular 2. However, navigating through the changes and rewrites can feel like traversing a confusing maze. All of the comprehensive guides I have come across date back to l ...

Utilizing Angular 2 Highcharts with Font Awesome to enhance custom button functionality

I came across this example demonstrating how to add font awesome icons to custom buttons in highcharts. http://jsfiddle.net/zfngxoow/6/ (function (H) { H.wrap(H.Renderer.prototype, 'label', function (proceed, str, x, y, shape, anchorX, ...

Ways to trigger an event based on the outcome of a pop-up window

In my current project, I am working on a component that includes three buttons: two default options and an additional modal dialog option for more advanced choices. When one of the default buttons is clicked, the component emits an event based on the selec ...

Showing particular URL text upon opening a new window using JavaScript

I've encountered an intriguing scenario. In my application, there's a feature that triggers a new window/tab to open when a button is clicked. Upon opening, a predefined HTML page is shown to the user with a specific URL set. I'm curious abo ...

Using Angular 2 to Create Nested ngFor Loops

I'm facing an issue that I can't seem to resolve. I attempted to use *ngFor in my code, but it seems that I am making a mistake with nested ngFor loops. To illustrate what I need to achieve, I ended up writing some messy code just to show the str ...

Utilize ServersideProps to input data into the server-side

Can data be retrieved from the server-side configuration file on the client using getServersideProps() in Next.js? What is the best way to send this data as props or retrieve it in a different manner on the client side? I attempted to use publicRuntimeCo ...

Implementing rxjs switch between multiple observables

As I work with 2 observables, my goal is to retrieve a value from Observable1, then disregard it and only anticipate a value coming from Observable2. After that, repeat the process by getting a value from Observable1 once more, and so on. I am exploring w ...

SCORM-compliant Angular web application bundle

As I work on my angular web project, I am looking to create a SCORM package in order to easily integrate it into any LMS system. I have a few questions regarding the packaging process and compatibility: What is the best way to package my project for SCORM ...

Learn how to iterate over a JSON object using TypeScript in Angular5 to generate an array of objects

Here is a sample JSON code that includes an array "Customers" with objects and arrays nested inside: This is my JSON code snippet: { "Customers": [ { "customerData": { "secondLastName": "Apale", "firstLastName": "Lara", ...

How can TypeScript associate enums with union types and determine the type of the returned object property?

I have a unique enum in conjunction with its corresponding union type. type User = { name: string, age: number } export enum StorageTypeNames { User = "user", Users = "referenceInfo", IsVisibleSearchPanel = "searchPane ...

Connecting Multiple Relationships with Many-To-Many Matches

My database consists of the following entities: @Entity class User { @ManyToMany(type => Group) @JoinTable() groups: Group[]; } @Entity class MediaObject { @ManyToMany(type => Group) @JoinTable() groups: Group[]; } @Entity ...