Loading data in an Angular Material data table is proving to be a challenge

Recently, I decided to try using Angular Material Data table in my project. With some tweaks, I was able to successfully load the table header, however, I encountered an issue where the data was not displaying as expected. Upon checking the console log, the only message displayed was:

Observable -> MapOperator -> thisArg: undefined

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { AngularFirestore } from '@angular/fire/firestore';

@Component({
  selector: 'app-tasks',
  templateUrl: './tasks.component.html',
  styleUrls: ['./tasks.component.scss']
})
export class TasksComponent implements OnInit {
  tasks: Observable<any[]>;

  displayedColumns = ['description', 'note'];
  dataSource: MatTableDataSource<Tasks>;

  constructor(private db: AngularFirestore) {}

  ngOnInit() {
    this.tasks = this.db
      .collection('tasks')
      .snapshotChanges()
      .pipe(
        map(actions => {
          return actions.map(a => {
            const data = a.payload.doc.data() as Tasks;
            const id = a.payload.doc.id;
            return { id, ...data };
          });
        })
      );

  console.log(this.tasks);
  return this.tasks;
  }
}

export interface Tasks {
  description: string;
  note: string;
}

Below is the snippet of HTML code that corresponds to the mentioned TS file:

<mat-table #table [dataSource]="dataSource">
  <ng-container matColumnDef="description">
    <mat-header-cell *matHeaderCellDef> description </mat-header-cell>
    <mat-cell *matCellDef="let task">{{task.description}}</mat-cell>
  </ng-container>

  <ng-container matColumnDef="note">
    <mat-header-cell *matHeaderCellDef> note </mat-header-cell>
    <mat-cell *matCellDef="let task">{{task.note}}</mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>

Currently, I am working with Angular 7 along with the latest package versions. Despite having records in the database, I can't seem to figure out why the data isn't appearing on the Angular Material Data table. Any ideas on what might be causing this issue?

Answer №1

Have you considered implementing the following code snippet?

    <mat-table class="highlight" #table [dataSource]="dataSource" matSort>
 <!-- Dynamic      -->
        <ng-container *ngFor="let col of displayedColumns" matColumnDef={{col}}>
          <mat-header-cell *matHeaderCellDef mat-sort-header>{{col.replace('_', ' ')| titlecase }} </mat-header-cell>
          <mat-cell *matCellDef="let Exception">
            <span>{{Exception[col]}}</span>
          </mat-cell>
        </ng-container>
 <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
      </mat-table>

TS

        import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';

/* dataSource: MatTableDataSource; replace this with */

dataSource = new MatTableDataSource();
             this.dataSource.data = this.Task;

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

Unclear error message when implementing union types in TypeScript

Currently, I am attempting to define a union type for a value in Firestore: interface StringValue { stringValue: string; } interface BooleanValue { booleanValue: boolean; } type ValueType = StringValue | BooleanValue; var value: ValueType = { bo ...

How can you modify the encapsulation of a third-party component in an Angular application?

Utilizing AngularElements with native encapsulation allows bs4 components to be used in a bs3 project. For example: @Component({ selector: 'app-my-button', templateUrl: './my-button.component.html', encapsulation: ViewEncapsulati ...

Complete set of keys within a type

In my TypeScript project, I am working with an API (specifically OData API) to retrieve data. This API allows the selection of specific fields to retrieve. For example, api/some/getbyid(42)?$select=x,y,z can be used to get fields x, y, and z, along with s ...

Persist user input data from a React form to a Firebase real-time database for seamless

I have completed this code and it is correctly displaying console output when using the console.log() method. However, the issue lies in that the data is not being stored in my database. There are no visible errors indicated but the data is not being save ...

If I don't utilize dependency injection in Angular, it prompts me for arguments

Attempting to implement a service like this but encountering some issues translateService = new TranslateService(); An error message pops up stating that there are 9 missing arguments. However, when I modify it to look like this constructor(private trans ...

Dynamic TenantID Recognition in Angular for Effortless Data Retrieval and Updating

I'm facing an issue in my Angular app where I have to validate the tenantId and fetch relevant data when the page is reloaded. Currently, I have scattered this logic across multiple components in my code. However, I want to streamline this process to ...

Deciphering TS2345: "The argument supplied, known as 'typeof MyComponent', cannot be assigned to the specified parameter type"

I am facing an issue while attempting to integrate a Typescript React component with react-onclickoutside. The error message that I encounter is as follows: TS2345: Argument of type 'typeof MyComponent' is not assignable to parameter of type &apo ...

What is the best way to sort through an array depending on a specific sequence of elements provided

I am trying to create a custom pipe in Angular 5 that filters an array of events based on a given sequence. For instance, if my data is: ["submit", "click", "go_back", "click",...] I want to filter this data based on up to three inputs. If input ...

Retrieve the output of the subscribe function in Angular 8 service

I have a service with a method that retrieves the profile image of a user. users.service.ts getPictureProfile() { const headers = new HttpHeaders({ . . .}); const options = { headers }; const body = {...}; return this.http.post(environmen ...

Field that only permits numerical input without triggering events for other characters

I've encountered some issues with the default behavior of the HTML number input and I'm looking to create a simple input that only allows numbers. To address this, I have developed a directive as shown below: import { Directive, ElementRef, Hos ...

Angular 4 Bootstrap 4 Collapsible Navigation Bar

Struggling for a while now trying to achieve the exact functionality I desire. Within my Angular Universal App, there is a vertical navigation bar at the top that I want to make responsive for mobile devices. I am utilizing Bootstrap 4 Alpha 6 and ngx-boot ...

Can a custom subscribe() method be implemented for Angular 2's http service?

Trying my hand at angular2, I discovered the necessity of using the subscribe() method to fetch the results from a get or post method: this.http.post(path, item).subscribe( (response: Response)=> {console.log(response)}, (error: any)=>{console.l ...

Is it possible to achieve real-time two-way data binding in a reactive form by passing values from one formgroup to another formgroup? If so, how

There are 2 FormGroups named orderForm and parcelForm on a page. The parcelForm is generated dynamically within a FormArray. In the parcelForm, there are FormControls like net_weight and gross_weight, while the OrderForm has FormControls such as total_net_ ...

Swiping in Angular2 gets a new twist with Swiper typings

Having trouble importing typings for Swiper into my Angular 2 project. After installing Swiper and its typings using npm, I tried including Swiper in my component like this: import { Swiper } from 'swiper'; However, Atom displays an error: ...

Setting up Identity Server 4 integration with Ionic 2

Currently, I am in the process of setting up Identity Server to function with Ionic 2. I am a little confused about how to set up the Redirect URLs specifically for testing purposes in the browser. Furthermore, I am updating and integrating an OIDC Cordov ...

What could be causing the Material AngularJS (CSS) on my website to not function properly, unlike the demo that was

I am completely new to AngularJS and I want to incorporate the material design version of AngularJS for developing a form. I followed the beginner's guide and attempted to create something, but it didn't turn out like the one on the website. So, ...

Which property within the <mat-option> element is used for toggling checkboxes on and off?

I'm experimenting with dynamically checking/unchecking a checkbox in mat-option. What attribute can I use for this? I've successfully done the same thing with mat-checkbox using [(ngModel)]. Here's the snippet of my code: app.component.html ...

Combining nested Observables within an outer array without using inner subscribe (RxJS)

Looking at the TypeScript functions below, which are used for async HTTP-Calls: public retrieveAllMembersIdsFromGroup(groupId: string): Observable<string[]> public retrieveMember(memberId: string): Observable<Member> How can these be combined ...

Updating Elements in an Array Using JavaScript is Not Functioning as Expected

In my Angular application, I have included some lines of TypeScript code which involve Boolean variables in the constructor and an array of objects. Each object in this array contains input variables. selftest: boolean; failed: boolean; locoStateItem ...

Utilizing Android AccountManager for Firebase authentication

If you're like me and want to develop an Android app utilizing Firebase, check out the demo code for a login screen provided by Firebase on GitHub here. Instead of having users enter their account information manually, I'm interested in allowing ...