Angular Material Datatables - Issue with Paginating Data from Firestore

Data has been retrieved from Firestore and transformed into an Observable array with the InvoiceItem type.

The data loads correctly onto the datatable, but there seems to be an issue initializing the paginator with the array's length. This could possibly be because the data is resolved asynchronously, although I'm not entirely certain about this.

Could you please confirm if my assumption is correct?

import { Component, OnInit, AfterViewInit, ViewChild, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MatPaginator, MatTableDataSource, MatSort } from '@angular/material';
import { Observable } from 'rxjs/Observable';

import { AngularFireDatabase } from 'angularfire2/database';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';

import { AuthService } from '../../services/auth.service';
import { InvoiceService } from '../invoice.service';

import { Invoice } from '../invoiceModel';
import { InvoiceItem } from '../invoiceItemModel';

@Component({
  selector: 'app-view-invoice',
  templateUrl: './view-invoice.component.html',
  styleUrls: ['./view-invoice.component.scss']
})

export class ViewInvoiceComponent implements OnInit, AfterViewInit {

  userId: string;
  invoiceId: string;
  invoice: Invoice;
  itemsCollection: AngularFirestoreCollection<InvoiceItem>;
  items: Observable<InvoiceItem[]>;
  itemsData = new MatTableDataSource<InvoiceItem>();

  tableColumns = [
    'description',
    'quantity',
    'unitPrice',
    'subtotal',
    'taxCode',
    'tax',
    'total'
  ]

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(private authService: AuthService, private invoiceService: InvoiceService, private db: AngularFirestore, private route: ActivatedRoute) {
    this.userId = this.authService.user.uid;

    this.route.params.subscribe(params => {
        this.invoiceId = params.id;
    })

    this.db.collection('/users').doc(this.userId).collection('/invoices').doc(this.invoiceId).ref.get().then(snapshot => {
        this.invoice = snapshot.data() as Invoice;
    })

    this.itemsCollection = this.db.collection('/users').doc(this.userId).collection('/invoices').doc(this.invoiceId).collection('/items');

    this.items = this.itemsCollection.snapshotChanges().map(changes => {
        return changes.map(a => {
            const data = a.payload.doc.data() as InvoiceItem;
            data.id = a.payload.doc.id;
            return data;
        })
    })

  }

  ngOnInit() {
    this.getItems().subscribe(data => {
        this.itemsData.data = data;
        this.itemsData.paginator = this.paginator;
        this.itemsData.sort = this.sort;
    })
  }

  ngAfterViewInit() {

  }

  getItems() {
    return this.items;
  }

}

Answer №1

It appears that the pagination and sorting functionalities only function properly when using .valueChanges() with the main collection. However, while this method allows for pagination and data sorting, it does not support retrieving document $keys.

ngAfterViewInit() {
    this.itemsCollection.valueChanges().subscribe(data => {
        this.dataSource = new MatTableDataSource(data);
        this.dataSource.sort = this.sort;
        this.dataSource.paginator = this.paginator;
    });
}

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

I am currently attempting to deploy my React application using Vercel. I followed all the necessary steps in my terminal, but unfortunately encountered an error at the end: "Error: Command 'npm install' exited with 1"

Here are the problem details: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5022353133247d2333223920242310657e607e61">[email ...

The 'validate' property within the 'MappingService' class cannot be assigned to the 'validate' property in the base class 'IMappingService' in typescript version 2.8.0

Currently, I am utilizing the AngularJS framework (version 1.5.8) in tandem with the latest TypeScript files (2.8.0). However, upon updating to the newest version of TypeScript, the code below is failing to compile. The IMappingService interface: export ...

The type does not contain a property named 'x' - Error in Promise syntax - TS2339

I encountered a problem while working with Typescript that I couldn't quite figure out. Although I came across similar issues in other topics, I'm still struggling to find a solution for my particular issue. I can easily log userCredential.user.m ...

Transferring FormArray validators from a child component to a parent component in Angular version 8

UPDATE: I successfully implemented data passthrough and validation by refactoring the email-phone-input.component.ts to utilize ControlContainer, obtain the FormGroup from the parent component, and manage FormArray controls. Stay tuned for the updated repo ...

multiple event listeners combined into a single function

I'm looking to streamline my button handling in JavaScript by creating just one function that can handle all the buttons on my page. Each button will trigger a different action, so I need a way to differentiate between them. I thought of using one eve ...

Is it possible to globally modify the component reference <dropdown-component> name in Angular during runtime in a dynamic manner?

I am currently working on an application that utilizes a component called "dropdown-component" throughout its pages. However, due to specific business requirements, I have been tasked with replacing "dropdown-component" with "custom-dropdown-component". Un ...

TSLint Errors Update: The configuration provided cannot locate implementations for the following rules

After upgrading my tslint to version 4.0.2, I encountered numerous errors like the ones shown below: Could not find implementations for the following rules specified in the configuration: directive-selector-name component-selector-name directi ...

Issue encountered during deployment where Firebase functions are causing an exception to be

After creating Firebase functions to send notifications on data changes in Firestore, I encountered a problem when trying to transfer the code from my old computer to a new one. The commands are now throwing errors and I have been attempting to fix them fo ...

How can you annotate and inherit a class method that returns an array of itself?

In the following example, I present a simplistic representation of code that may not align with standard HTML or front-end conventions. Please excuse any confusion this may cause. TL, DR I am facing challenges in specifying a return type for a method tha ...

Incorporate an external library

I am currently facing a challenge in my angular2 project where I need to import a 3rd party library. Here are the steps I have taken so far: ng new myproject npm install --save createjs-easeljs npm install @types/easeljs However, I am stuck at this poin ...

Troubles arise with a Web API ASP .NET / Angular2 Session hosted on Azure

Hello, this is my first question here so please let me know if something doesn't fit. Currently, we are working on developing a Web API using C# and Angular2. One of the features requires the session to be efficient, but despite going through numerou ...

There is no XHR request sent when invoking the http function

I am facing challenges in configuring a service in angular2 to interact with a REST backend. My attempt at setting up a basic example for sending requests to a rest backend and handling the response seems to be on track. The Service is being called correc ...

Create a TypeScript class object with specified constructor arguments

I've been working on a function that is supposed to execute the init method of a class and then return an instance of that class. However, I'm running into issues with maintaining the constructor and class types. This is what I have tried so far ...

Updating the value in React context does not result in the value being updated

I am in the process of developing a simple routing system where users can either be authenticated or not. I have been using hooks to implement this functionality, but so far, it has not been as successful as I hoped for. authProvider.tsx import React, {Di ...

Customizing default attribute prop types of HTML input element in Typescript React

I am currently working on creating a customized "Input" component where I want to extend the default HTML input attributes (props). My goal is to override the default 'size' attribute by utilizing Typescript's Omit within my own interface d ...

Typescript is struggling to accurately infer extended types in some cases

My goal is to optimize the body of a NextApiRequest for TypeScript. I currently have this code snippet: // This is a type from a library I've imported export interface NextApiRequest { query: Partial<{ [key: string]: string | string[]; ...

Is there a way to execute the function of component2 that is embedded in the HTML display of component 1?

There are 2 components in my application - principal and menu. The menu component includes a JSON object and HTML code where clicking on an element should trigger a function in the principal component. Upon clicking this function, the selected object shoul ...

What is the equivalent of Typescript's Uint8Array and Uint16Array in Python?

new Uint8Array(new Uint16Array([64]).buffer) How can I achieve a similar data structure in pure Python? What is the equivalent of Uint8Array/Uint16Array? I am extracting a buffer from a Uint16Array type here and converting it to a Uint8Array, but I am un ...

issue with uploading files in angular 7

Currently, I am facing an issue with Angular 7 where the input type "file" is not working as expected. However, in Angular 6, everything works fine. When submitting the input file type data in Angular 6, I receive a field list like this: https://i.sstat ...

Tips for resetting a form after submission

Hey there, I'm currently working with Angular 7 and facing an issue with form submission. After submitting the form successfully, I want to reset it without triggering the required validation for input fields. Here's a snippet of my TypeScript co ...