HTML template failing to retrieve data from Angular dataSource

My goal is to import data from an Excel file into my angular application. I have successfully retrieved the data from the Excel file, parsed it to extract the necessary columns, and stored it in an array within my service.ts file.

I call the service from my component.ts file as a return, where I confirm the data retrieval using console.log().

To display the data as a MatTableDataSource in the child component, I am utilizing @Output() to pass the data to the child.

I have tested that the HTML template functions properly by loading the data into a json-server and retrieving it through a service.

Despite several attempts to troubleshoot, the datasource is not displaying on the HTML. Although my HTML screen indicates the presence of records, the actual data rows are not visible.

Console.Log information:

bom-load:
[]
0: {qty: "6", mfg: "Mencom", partNumber: "1321-3R8-C", desc: "480V 3-PHASE AC DRIVE REACTORS, OPEN TYPE, 8A, 3 HP Drive"}
1: {qty: "1", mfg: "AB", partNumber: "1756-EN2T", desc: "1756 CONTROL LOGIX ETHERNET / IP BRIDGE MODULE (128 TCP/IP CONNECTIONS)"}
...

bom-list.component.ts line 43 log output:
bom-list: 
MatTableDataSource {_renderData: BehaviorSubject, _filter: BehaviorSubject, ...}

Image of html table trying to use data loaded from Excel
<a href="https://i.sstatic.net/aojbf.png" rel="nofollow noreferrer"></a>

Image of static data using this.getAllBomItems
<a href="https://i.sstatic.net/AmkJa.png" rel="nofollow noreferrer"></a>

Interesting development:
by adding; as suggested; ngOnChanges(), I now get data, but ONLY after clicking the pagination buttons.

 

Answer №1

Important Update

To enhance performance, consider using ngOnChanges instead of ngOnInit in your child component.

Additionally, don't forget to utilize ChangeDetectorRef.

constructor (
  ...
  private cdr: ChangeDetectorRef
) {}

ngOnChanges() {
    this.dataSource = new MatTableDataSource(this.data);
    this.dataSource.paginator = this.paginator;
    this.cdr.detectChanges();
}

Please Note

<div *ngIf="data != null">

Modify the above line to:

<div *ngIf="data">

Your data value is currently undefined, so using *ngIf="data != null" will result in a truthy expression. As a result, the ngOnInit lifecycle hook in your child component will be triggered without the presence of valid data.

Furthermore, remember to adjust the following code block as well:

getAllBomItems() {
    this.bomService.getList().subscribe((response: any) => {
      this.dataSource = new MatTableDataSource(response);
      // this.dataSource.data = response; <- This line alone won't trigger change detection for your table. It's crucial to replace the entire dataSource object.
    });
  }

Answer №2

Attempt using ChangeDetectorRef in the component that includes your data table and trigger it this way:

  constructor(private cdRef: ChangeDetectorRef) {
  }

//once new data is added to the table
this.cdRef.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

Is it possible to use the `fill` method to assign a value of type 'number' to a variable of type 'never'?

interface Itype { type: number; name?: string; } function makeEqualArrays(arr1: Itype[], arr2: Itype[]): void { arr2 = arr2.concat([].fill({ type: 2 }, len1 - len2)); } What is the reason for not being able to fill an array with an ob ...

Uploading Files with Django Rest Framework and Angular 2

I am working with Django Rest Framework and Angular 2 to implement a file upload feature. Below is my code structure for handling files. Can anyone point out where I might be going wrong? Any help is greatly appreciated. Thank you! Django file: view cla ...

Transform the request in an Angular2 and jQuery Ajax POST call

I'm in the process of migrating my application from angularJS to angular2 and I've encountered a roadblock with an ajax POST call. return $.ajax({ url: "http://www.url.com", crossDomain: true, contentType: 'applicati ...

What is the essential setup needed for a bootstrap dropdown list?

I'm currently working on an Angular project and I've been trying to implement the dropdown navbar from Bootstrap. I simply copied the code from here, but unfortunately, the dropdown feature isn't functioning properly for me: // I've att ...

Require a property to be mandatory depending on the value of another property within a generic interface

Looking for a way to have one property affect the others in a react component interface? Here's an example of what I'm trying to achieve: export interface IMyAwesomeComponentProps<T = {}> { className: string defaultPath?: ISomeOthe ...

Error TS2304: Unable to locate identifier 'QRScanner'

I am currently exploring https://www.npmjs.com/package/cordova-plugin-qrscanner in order to implement a QR scanning feature in my mobile application. As part of the initial steps, I have written the following code snippet in my typescript file: function o ...

Creating a dynamic form in Angular based on user input

I am in the process of creating a dynamic web form where the user's input will determine the subsequent form inputs that are generated. For example: <mat-form-field> <mat-select placeholder="Type" [(ngModel)]="row.Type" (change)="Typ ...

Integrating fresh components into a JSON structure

I've been attempting to insert a new element into my JSON, but I'm struggling to do it correctly. I've tried numerous approaches and am unsure of what might be causing the issue. INITIAL JSON INPUT { "UnitID":"1148", "UNIT":"202B", "Sp ...

Certain information is failing to be added to the list

userSPMSnapshot.forEach((doc) => { console.log(doc.id, "=>", doc.data()); userSPMList.push(userSPM.fromFirestore(doc)); }); console.log(userSPMList) I'm encountering an issue where some fields in my data lose their values when I p ...

Unselect all options in Angular's multiple selection feature

Objective: My goal is to ensure that when I invoke the myMethod() function, all options are unselected. Current Issue: Currently, calling myMethod() will only deselect the last option, leaving the others selected if they were previously selected. Possibl ...

Is it possible to safely change the name of an Angular project?

Looking to completely rename an Angular 8 project from top to bottom - changing the folder name and every line of code that references the original project name. I have seen in past posts (and previous versions of Angular) that there was no CLI command fo ...

The attribute 'date' is not found within the class 'EmployeeScheduleExceptionModel', however, it is present in the parent class from which it inherits

I am working on a TypeScript project and I have defined my configurations in the tsconfig.json file as shown below: { "include": ["src*"], "compilerOptions": { "target": "es2021", &q ...

How to upload files using 3 input fields in Angular?

Seeking assistance on uploading 3 files using 3 different inputs. I'm a beginner in Angular, so please excuse any naive inquiries. Here is the code snippet: BookFormComponent.ts: export class BookFormComponent implements OnInit { audioFile: File ...

Having difficulty incorporating TypeScript into Vue

A little while ago, I set up a vue project using vue init webpack . and everything was running smoothly. Recently, I decided to incorporate typescript and ts-loader. I created a file in the src directory with the following content: declare module '* ...

What is the best way to obtain a comprehensive list of nested routes specified in the router configuration?

In my Angular 2 App, I have a dashboard route that contains several child routes. { path: 'app/:property', component: DashboardComponent, canActivate: [AuthGuardService], children: [ { path: 'home', component: HomeComponent } ...

A dynamic d3 line chart showcasing various line colors during transitions

I have implemented a d3 line chart using this example as a reference: https://codepen.io/louisemoxy/pen/qMvmBM My question is, is it possible to dynamically color the line in the chart differently based on the condition y > 0, even during the transitio ...

What is the reason for ngbDatepicker converting numbers into dates upon input?

This specific HTML snippet has a unique feature: when the input number is set to "2", it automatically changes to 04.01.2001: <div class="input-group"> <input [ngClass]="{'invalid-input': editFor ...

Injection of environmental variables into app services

Through the use of Nx, I have created multiple apps that each have their own environment with different API URLs. The Nx Workspace library includes shared services that are utilized among all apps, however, it is necessary to pass the environment-api-url w ...

Troubleshooting the ngx-image-zoom dependency error: How to resolve the unresolved dependency issue

When working on an angular project in version 10, I encountered challenges while installing the ngx-image-zoom component due to dependencies with angular 10. Despite this, I managed to resolve the issues. However, in my current project using angular 11, I ...

Implementing a dependent <select> within an HTML table is a useful feature to enhance user experience and organization of

I have set up a table with editable columns where values can be selected from a drop-down menu. I achieved this by using HTML select. The options in the 'Category tier 2' column are based on the selection made in the 'Category tier 1' c ...