Guide on showcasing DataSource with material table in Angular 8

Currently, I am utilizing Angular material table in my project, but I am having trouble displaying the dataSource content on the screen. Below is the snippet of code I am working with:

In my evento-table.component.ts file, I have data being requested from the server:

  dataSource: EventoTableDataSource;

  eventos: Array<any> = new Array();

  constructor(private eventosService: EventosService) { }

  displayedColumns = ['pais', 'regiao', 'sensor', 'timestampDt', 'valor', 'status'];

  ngOnInit() {
    this.listarEventos();
    this.dataSource = new EventoTableDataSource();
    console.log('dataSource', this.dataSource);
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.table.dataSource = this.dataSource;
  }

  listarEventos() {
    this.eventosService.listarEventos().subscribe(eventos => {
      this.dataSource.data = eventos;
      return eventos;
    });
  }
}

Now, the challenge I am facing is how to utilize the dataSource in order to display the data on my view:

Here is the content of evento-table-datasource.ts file:

// TODO: replace this with real data from your application
const EVENTOS: EventoTableItem[] = [{
  id: 1,
  pais: 'Brasil',
  regiao: 'Sudeste',
  sensor: '001',
  valor: 3000,
  status: 'Processado',
  timestampDt: '2019-06-19T00:00:00Z'
  }];

export class EventoTableDataSource extends DataSource<EventoTableItem> {
  data: EventoTableItem[] = EVENTOS;
  paginator: MatPaginator;
  sort: MatSort;

  constructor() {
    super();
  }

  connect(): Observable<EventoTableItem[]> {
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  disconnect() {}

  ...
}

Lastly, here is how I have set up my table visualization:

<table mat-table [dataSource]="eventos" class="full-width-table" matSort aria-label="Elements">

Answer №1

When running the connect function, it may encounter variables with no value or undefined.

data: EventoTableItem[] = EVENTOS;
paginator: MatPaginator;
sort: MatSort;

This is why an undefined value error can occur, specifically due to uninitialized this.paginator.page.

It is possible that this issue arises because the connect function is called before:

ngAfterViewInit() {


     this.dataSource.sort = this.sort;
        this.dataSource.paginator = this.paginator;
        this.table.dataSource = this.dataSource;
      }

Is there a specific reason for placing this logic in ngAfterViewInit instead of ngOnInit()?

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

The event listener for 'end' is not executing in a Node.js Firebase and Nylas Express application

I am currently working on setting up webhooks with Nylas. In their provided example, there is a middleware code that I am implementing in my TypeScript project using Firebase as the endpoint. When testing locally with ngrok, the middleware functions prop ...

Troubleshooting: Fixing the "@angular/core" module not found error in Visual Studio 2019

As I embark on my Asp.Net Core Project with Angular template, I encounter an issue with every import row that includes '@angular/...'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-bro ...

Redirecting to an Unverified Website

I encountered an issue in my service.ts file where VeraCode code scan is failing Flaws by CWE ID: URL Redirection to Untrusted Site ('Open Redirect') (CWE ID 601)(16 flaws) Description The web application is vulnerable to URL redirection attacks ...

Updating an existing Observable asynchronously using the pipe method

My scenario involves working with an Observable that is subscribed to via the async-pipe. <ng-container *ngIf="invitations$ | async as invitations"> I initialize this Observable in the ngOnInit function: this.invitations$ = this.getInvitat ...

What methods can be used to test included content in Angular?

When testing an Angular component that includes transclusion slots utilizing <ng-content>, it becomes challenging to verify if the transcluded content is correctly placed within the component. For instance: // base-button.component.ts @Component({ ...

Arranging JavaScript object by object properties (name)

Can anyone assist me with my training? I am currently learning JavaScript (Js) and TypeScript (Ts) by working with an external public API. After successfully fetching and displaying my data, I now want to implement sorting functionality. My goal is to sor ...

I'm encountering difficulty trying to set up sweetalert2 in Angular

Please provide an image description I'm facing a problem and I need assistance. Despite following various installation guides, I have been unable to find a resolution. Please provide an image description ...

Traverse a tree structure of nested child objects in an Angular template using a JavaScript

Check out the Javascript object below: { "id": "1554038371930_ajhnms9ft", "name": "CPS", "nodes": [ { "id": "1554038905938_le34li2cg", "name": "Consumer Journey", "nodes": [ { ...

Tips for managing various potential return types in TypeScript?

In my research on the topic, I came across a discussion thread about obtaining the local IP address in Node.js at Get local IP address in Node.js. In that thread, there is a code snippet that I would like to incorporate: import net from 'net'; c ...

The complete Angular 2 application fails to load when accessed using a custom domain name

I've been struggling for the past few days trying to solve a strange issue. When I try to access my Angular 2 app using a domain name (example.com), it gets stuck on the loading screen. However, if I try accessing the same app without nginx, it loads ...

Angular QueryList produces varying types compared to what is obtained from a click event listener

I'm experiencing an issue when comparing the content of a list of QueryList<ElementRef>. I need to differentiate certain elements in order to create a closing logic for a menu. In my toolbar, I have buttons that are Angular Material buttons of ...

Observable function encountering difficulties returning nested values

I've been working on a function that returns an observable. test(id: int): Observable<Group>{ this.http.get('test/').subscribe( (result:any) => { resultingVal = Group.fromJson(result.group); }); } Right now, the function ...

Guide to integrating a third-party library with Angular 4 for service implementation

I've been attempting to integrate collect.js into my Angular 4 project developed with the Angular CLI. Although I have imported the package using the following code snippet, I am struggling to understand how to utilize it effectively: import * as Col ...

Angular 2 - Updating a specific value with a click

Using the code snippet below, an autocomplete feature based on Google Places API can be implemented. As characters are typed into the input fields, the code fetches and displays a list of place names. The goal is to have the selected 'place' repl ...

Creating a FormArray with multiple dimensions in Angular 4: A step-by-step guide

For my dynamic form project, I am using the ng-formly npm tool to create a form with sections and tabs, all controlled by a single submit button. According to the library's documentation, I have defined an interface called TabType which specifies diff ...

Step-by-step guide on building a wrapper child component for a React navigator

When using the Tab.Navigator component, it is important to note that only the Tab.Screen component can be a direct child component. Is there a way in Typescript to convert or cast the Tab.Screen Type to the TabButton function? const App = () => { retur ...

Using Angular Platform-server (Universal) to route with query parameters

I've been struggling to describe a route with get parameters in my platform-server/universal application, but haven't had any luck so far. Does anyone have suggestions on how to achieve this? Based on my understanding of express routing, I atte ...

Unraveling Angular2 Dependency Injection: Decoding the mysterious syntax seen preceding certain injected package names (e.g. 'providers = [...SomeProvider]')

As I delve into learning Angular2, I have stumbled upon a new syntax for injecting providers. providers : [SomeProvider], Interestingly, some packages are now using a "..." before the provider name like this: providers : [...SomeProvider], This got me ...

The parameter type '(value: any) => any[]' does not match the expected parameter type 'string[]'

I'm encountering an issue where I can't push a value to a state array due to a TS error. Let me highlight the relevant components where the error occurs. The error specifically lies in the child component, within the handleValue(value => [...v ...

Confirm that the attributes of a JSON object align with an Enum

Having a Lambda function that receives a JSON object from the Frontend over HTTPS, I need to perform validation on this object The expected structure of the body should be as follows (Notifications): interface Notifications { type: NotificationType; f ...