Struggling to populate a table with data

I've previously sought help on this project and I'm still facing challenges. The code is messy with duplicate functions, making it hard to manage.

Currently, my main issue is fetching data from Firebase and updating a table with it.

 <div class="mat-elevation-z8">
  <table mat-table [dataSource]="dataSource">
    <ng-container matColumnDef="adminEmail">
      <th mat-header-cell *matHeaderCellDef> Email </th>
      <td mat-cell *matCellDef="let admin"> {{adminUser.adminEmail}} </td>
    </ng-container>
    <ng-container matColumnDef="adminNome">
      <th mat-header-cell *matHeaderCellDef> Nome </th>
      <td mat-cell *matCellDef="let admin"> {{adminUser.adminNome}} </td>
    </ng-container>            
    <ng-container matColumnDef="role">
      <th mat-header-cell *matHeaderCellDef> Role </th>
      <td mat-cell *matCellDef="let admin"> {{adminUser.role}} </td>
    </ng-container>
    <ng-container matColumnDef="update">
      <th mat-header-cell *matHeaderCellDef> Alterar </th>
      <td mat-cell *matCellDef="let admin">
          <a mat-icon-button (click)="editUser(admin)">
              <mat-icon>edit</mat-icon>
          </a>
      </td>
  </ng-container>
  <ng-container matColumnDef="delete">
      <th mat-header-cell *matHeaderCellDef> Apagar </th>
      <td mat-cell *matCellDef="let admin">
          <button mat-icon-button (click)="deleteUser(admin)">
              <mat-icon>delete</mat-icon>
          </button>
      </td>
  </ng-container>  
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
  <mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons>
  </mat-paginator>
</div>

I'm using material design for this task, so working with data from interfaces for the table is not an issue. However, fetching information from the database is proving to be problematic.

Here's a snippet of my component ts file:

adminUser: any = {
    adminNome: '',
    adminEmail: '',
    role: ''
  }

  allAdmins: AdminUser[] = [];
  selectedAdmins: any = [];
  submitted!: boolean;

  displayedColumns: string[] = ['adminEmail', 'adminNome', 'role', 'update', 'delete'];
  dataSource = new MatTableDataSource<AdminUser>(this.allAdmins);

  @ViewChild(MatPaginator) paginator!: MatPaginator;

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

  constructor(
    private adminService: AdminUserService,
    private dinamicaService: DinamicaService,
    private messageService: MessageService,
    private confirmationService: ConfirmationService,
    private router: Router) { 
      
    }


  ngOnInit(): void {
    this.inputName = <HTMLInputElement>document.querySelector('#dinName');
    this.inputDesc = <HTMLInputElement>document.querySelector('#dinDesc');
    console.log("oi")
    this.loadAdmins();
    console.log("oi")
    this.loading = false;
  }

  initializeTable(): void {
    this.adminService.getUsersLocal().subscribe(admin => {
      this.allAdmins = admin;
      this.dataSource = new MatTableDataSource<AdminUser>(this.allAdmins);
      this.dataSource.paginator = this.paginator;
    });
  }

  loadAdmins() {
    this.adminService.getUsersLocal().subscribe(res => {  //Mudar aqui
      this.allAdmins = res
      console.log(this.allAdmins)
    })
  }

The function in the service used to fetch data is as follows:

getUsersLocal(): Observable<AdminUser[]> {
    const booksRef = collection(this.firestore, 'admin-roles');
    return collectionData(booksRef, { idField: 'id' }) as Observable<AdminUser[]>;
  }

I've tried debugging the code with console.log statements but can't seem to identify the issue. The getUsersLocal() function returns the data array, so I suspect there might be a problem with the initializeTable() function.

https://i.sstatic.net/hjinL.png

What can I do to rectify this situation?

Answer №1

My experience with adding data to my tablet also had its challenges, specifically due to incorrectly populating the matrix.

Consider the following solution:

      dataSource = new MatTableDataSource<Model>();
      @ViewChild(MatPaginator, {static: true})
      paginator!: MatPaginator;
      @ViewChild(MatSort, {static: true})
      sort!: MatSort;
        
          ngOnInit(): void {
            this.getAll();
            this.dataSource.paginator = this.paginator;
            this.dataSource.sort = this.sort;
          }
        
             getAll() {
                this.service.get().subscribe((data: Model[]) => {
             //the data should be assigned to "datasource.data"
                  this.dataSource.data = [...data];  // essentially replacing the array with the new data       
                });
              }

I trust this advice proves beneficial to you. Best regards.

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

"Customize the appearance of a List Element in Material UI by changing

How can I modify the color of a specific material ui list item? <ListItemText primary={mspvar} secondary="buy"> ...

What are the different methods to display information in Angular?

list.component.ts import { Component, OnInit } from '@angular/core'; import { StudentAPIService } from 'src/app/services/student-api.service'; import { StudentModel } from 'src/app/model/student'; @Component({ selector: &ap ...

Is your Angular5 service failing to transmit data?

I have two components in my code, A and B. Component A contains a form with data that I want to send to component B. However, it seems like component B is not receiving any data. Here is the code for Component A: import { MyService } from 'path/my ...

Triggering an exception for numerous entries in a JSON dataset

When working with my JSON data, I encountered an issue where multiple records were present, but only one record was being displayed in the browser. I attempted to use NgFor to repeat the data, but unfortunately, I encountered an error. Below is the code s ...

Utilizing external clicks with Lit-Elements in your project

Currently, I am working on developing a custom dropdown web component using LitElements. In the process of implementing a feature that closes the dropdown when clicking outside of it, I have encountered some unexpected behavior that is hindering my progres ...

I need to access the link_id value from this specific actionid and then execute the corresponding function within the Ionic framework

I have a JavaScript code in my TypeScript file. It retrieves the attribute from a span element when it is clicked. I want to store this attribute's value in a TypeScript variable and then call a TypeScript function. Take a look at my ngOnInit method, ...

Using Material UI date picker with TypeScript: A Complete Guide

Well, I have to admit that I usually don't resort to putting 'any' as the type when I'm uncertain what to do, but right now, I'm starting to feel quite frustrated. I'm currently working with Material UI date picker in conjunct ...

Issue with Material UI grid not rendering properly in TypeScript environment

I've been trying to replicate a grid from material-ui using React and Typescript. You can see a live demo here. I modified the example to work with Typescript, so my demo.tsx file looks like this: Code goes here... If you check out the live demo, y ...

Tips for utilizing express in your typescript projects

I'm curious about the transition of definition files from tsd to typings, and now to @types. How can I incorporate @types in a node/express project? What is currently preferred and what's the reason for moving from tsd to typing and finally to @t ...

Tips for efficiently using the debounce feature of valueChanges in reactive forms to prevent entering a patching loop while saving for the first time

Currently, I am working on implementing a debounce feature for my form fields. The challenge arises when dealing with a fresh form that lacks an ID. Upon creating and retrieving the record from the database, it becomes necessary to update the form with the ...

Best practice in TypeScript for handling an Enum with a switch-case to assign a variable

Here's an issue I'm facing: I have a variable called Difficulty that is an Enum. Within a function, I need to set the configuration DifficultyConfig based on the value of Difficulty. The current solution I have in mind seems overly complicated: ...

Retrieving the last segment of a URL in Angular

How do I extract the last segment of a URL? For instance, from /item/:id/edit, I want to isolate edit or /edit. I came across this question on Stack Overflow, but it doesn't seem to work for me as I need to execute this code in the parent component a ...

The necessity of a fixed height parent for a horizontal Listview in Flutter

I am working with a horizontal Listview that is enclosed within a SizedBox. SizedBox( width: Get.width, height: 50, child: Obx( () => ListView.separated( shrinkWrap: true, padding: Margin.h16, scrollDirection: Axis.horizontal ...

Retrieve the Document Ids that meet the criteria specified in a Query

Looking to retrieve the document ID that matches a specific query in cloud Firestore? Here's how my database schema is structured: deyaPayusers/ AuthId User details Ph ...

Tips for creating dynamic amd-dependencies in TypeScript

Is there a way to dynamically load a Javascript language bundle file in Typescript based on the current language without using static methods? I want to avoid having to use comments like this for each bundle: /// <amd-dependency path="<path_to_bund ...

In Angular and Jasmine, it is important to note that when multiple actions are included within an it() function, they

I'm currently working on a test to ensure that each INPUT field is not empty. I seem to be facing some challenges in writing this test, which could be due to my lack of experience or the limitations of Jasmine when it comes to handling multiple action ...

What Causes mat-bottom-sheet-container to Overflow Instead of Remaining Anchored at the Bottom of the Mobile Screen?

I am encountering an issue with a popup window in my Angular app. Despite testing it on various screen resolutions using Chrome's DevTools Screencast, the popup appears correctly styled and positioned on mobile devices. However, when tested on a real ...

Infinite loop caused by Angular navigation within route guarding

The routes in my application are configured as shown below: {path: '', redirectTo: 'login', pathMatch: 'full'}, {path: 'todos', component: TodosComponent, canActivate: [AuthGuard]}, {path: 'add-todo', ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...

Introducing the Angular 2/4 Dashboard Widget Module!

I am currently developing the dashboard for my Angular 2 application and I am in search of an npm package that fits my requirements. I came across a link that provides similar functionalities to what I need, which is . I want to be able to add new w ...