Trouble displaying data from rest api in Angular Material's mat-table

I've been attempting to incorporate mat-table into my Angular 8 project, but I seem to be missing something. The data from my REST endpoint is showing up fine in the console output.

Here's my admin.component.html file:

    <table mat-table [dataSource]="dataSource">
        <ng-container matColumnDef="position">
                <th mat-header-cell *matHeaderCellDef> No.</th>
                <td mat-cell *matCellDef="let data"> {{data.position}} </td>
              </ng-container>

        <ng-container matColumnDef="USERNAME">
                <th mat-header-cell *matHeaderCellDef> USERNAME</th>
                <td mat-cell *matCellDef="let data"> {{data.username}} </td>
              </ng-container>

              <ng-container matColumnDef="BU">
                <th mat-header-cell *matHeaderCellDef> BU</th>
                <td mat-cell *matCellDef="let data"> {{data.BU}} </td>
              </ng-container>

              <ng-container matColumnDef="DURATION">
                <th mat-header-cell *matHeaderCellDef> DURATION </th>
                <td mat-cell *matCellDef="let data"> {{data.duration}} </td>
              </ng-container>

              <ng-container matColumnDef="PURPOSE">
                <th mat-header-cell *matHeaderCellDef> PURPOSE</th>
                <td mat-cell *matCellDef="let data"> {{data.remarks}} </td>
              </ng-container>

              <ng-container matColumnDef="apr">
                    <th mat-header-cell *matHeaderCellDef> Approve</th>
                    <td mat-cell *matCellDef="let row" >
                            <mat-checkbox >Approve</mat-checkbox>
                    </td>
                  </ng-container>

                  <ng-container matColumnDef="rej">
                        <th mat-header-cell *matHeaderCellDef> Reject</th>
                        <td mat-cell *matCellDef="let row" >
                                <mat-checkbox >Reject</mat-checkbox>
                        </td>
                      </ng-container>

              <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
              <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
            </table>
            <button mat-button color="primary" (click)="OnApprovalSubmit()">Submit</button>


And here's my ts file:

export interface UserData{
  position:number;
  username:any;
  BU:any;
  duration:any;
  remarks:string;

}

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

export class AdminComponent implements OnInit{
  displayedColumns: string[] = ['position','USERNAME', 'BU', 'DURATION', 'PURPOSE','apr','rej'];
  USER_DATA:any;

  constructor(public testService : TestService){}
  ngOnInit(){
    this.testService.getUserAccessDetails().subscribe(data =>{
      console.log(data);
      this.USER_DATA=data.USER_DATA;
      console.log(this.USER_DATA);

    })

  }


  dataSource = new MatTableDataSource<UserData>(this.USER_DATA);
  selection = new SelectionModel<UserData>(true, []);

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
  }

  checkboxLabel(row?: UserData): string {
    if (!row) {
      return `${this.isAllSelected() ? 'select' : 'deselect'} all`;
    }
    return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.position + 1}`;
  }

}

When I check the console, the data is displayed in the following format:

USER_DATA: Array(1)
0: {position: "01", username: "Name", BU: "Team", Duration: 3, remarks: "NA"}

However, I am not seeing any rows rendered without any errors. Any assistance on this issue would be greatly appreciated.

Answer №1

To effectively populate the mat-table, ensure that the result obtained, labeled as 'dataSource', is included inside the subscribe function. This is crucial as the dataSource is the key input parameter for the mat-table.

ngOnInit() {
    this.testService.getUserAccessDetails()
    .subscribe(data => {
         this.USER_DATA = data.USER_DATA;
         this.dataSource = new MatTableDataSource<UserData>(this.USER_DATA);
    });
}

Answer №2

If you prefer not to create a new MatTableDataSource instance inside the subscribe function, you can give this alternative approach a try.

export class AdminComponent implements OnInit{

  displayedColumns: string[] = ['position', 'NAME', 'DEPARTMENT', 'TIME','REASON','approved','rejected'];
  dataSource = new MatTableDataSource<UserData>();

  ngOnInit() {
    this.testService.getUserAccessDetails()
    .subscribe(data => {
         this.dataSource.data = data.USER_DATA;
    });
  }
}

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

Angular 7 swiper experiencing navigation issues

I have been attempting to implement the swiper slider but I am facing issues with navigating through slide content. You can find my code on stackblitz - swiper in the last horizontal tab. Here is the TypeScript code: ngOnInit() { var swiper = new Sw ...

Challenges with asynchronous form groups in Angular: comparison between Edge and Chrome

I've set up a FormGroup where certain fields need to be disabled or enabled based on whether a checkbox is checked or not. Initially, my code was working fine, but I encountered an issue when testing it on Microsoft Edge (only previously tested on Chr ...

Learn how to iterate over a JSON object using TypeScript in Angular5 to generate an array of objects

Here is a sample JSON code that includes an array "Customers" with objects and arrays nested inside: This is my JSON code snippet: { "Customers": [ { "customerData": { "secondLastName": "Apale", "firstLastName": "Lara", ...

Encountering net::ERR_FILE_NOT_FOUND error when trying to upload chunked files through Ionic4 and Angular HttpClient, even after several successful uploads

I am currently facing an issue while attempting to upload a large file (500+Mb, potentially larger) to our php server using an app developed with Ionic4, Angular, and Cordova on an Android 10 emulator. To tackle this, I have implemented a mechanism to uplo ...

Extending the Model class in TypeScript with Sequelize

Currently, I am tackling a legacy project with the goal of transitioning it to Typescript. The project contains models that are structured as shown below: import Sequelize from "sequelize"; class MyModel extends Sequelize.Model { public static init(seq ...

Looking for guidance on integrating REST API consumption features into Ionic Framework 3.x?

It's been a long time since I last used the ionic framework. The version I worked with was 1, where every page created with Ionic Creator had its own controller for adding JavaScript code to consume my REST framework. Now that I've downloaded th ...

Carousel-item height in Bootstrap 4.6

I am facing an issue with a component in Angular 14 using Bootstrap v4.6: <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div cl ...

Firebase authentication link for email sign-in in Angularfire is invalid

Currently, I am utilizing the signInWithEmailLink wrapper from AngularFire for Firebase authentication. Despite providing a valid email address and return URL as arguments, an error is being thrown stating "Invalid email link!" without even initiating any ...

The subscription for the second Observable in RxJS concatMap is triggered individually

I am currently developing an Angular 6 application. I want the app to display a loading animation whenever there is a change in the route or if there are any pending HTTP requests. To achieve this, I have set up two Observables as follows: For httpPendingR ...

Performing DTO validation in the controller before passing data to the service

My current challenge involves implementing validation in a PUT request to update data stored in MongoDB: DTO: export enum reportFields { 'startDate', 'targetDateOfCompletion', 'duration', } export class updateS ...

Typescript: The .ts file does not recognize the definition of XMLHttpRequest

I have encountered an issue with a .ts file containing the following code: var xhttp = new XMLHttpRequest(); After running the grunt task to compile the ts files using typescript, no errors were reported. However, when I attempt to instantiate the class ...

What could be causing the disappearance of the top and bottom lines in jquery datatable after the data details are

After setting up a screen with a jquery datatable that loads correctly, I noticed an issue. When I edit the details of a record and return to the table, only the row containing the table is visible. Here is my table declaration: $(document).ready(() => ...

Transfer a file using fetch (POST request) within a TypeScript React component

i am trying to send a file to an api using fetch. this is the api: and here is how it wants to be handled: You can perform Ogre transformations directly by making a HTTP POST request: Convert to GeoJSON http://ogre.adc4gis.com/convert with the following ...

How to make text dynamically shrink with TailwindCSS class 'flex-shrink-0'

I've designed an 'Album' (React) component to showcase album artwork, name, and release date in a card-like format. This component consists of two divs - one for the photo and the other for text. Each artist's discography displays multi ...

Managing copious amounts of data in an Angular project using a Restful API

After developing my own Restful API within a Laravel project, I am faced with the challenge of efficiently managing large amounts of data returned by the API in order to display it on an Angular front-end project. For instance, when using the GET method t ...

Tips for building a diverse array of data types and effectively utilizing them based on their specific type in Typescript

Trying to store both custom types, Graphic and Asset, in the same array is proving to be a challenge. The goal is to access them and retain their individual type information. const trail: Array<Graphic | Asset> = []; for (let index = 0; index < t ...

Passing a username and password to an API in Angular 6: Step-by-step guide

Can someone assist me with this problem? I am struggling to pass the username and password in my API request for a list of homes. Every attempt I've made has resulted in an unauthorized access error. How do I correctly include the user credentials (pe ...

What is the best way to assign an index signature to a plain object?

Currently, I have this object: const events = { i: 'insert', u: 'update', d: 'delete' }; I am struggling to assign an index signature to the object. When I try the following: export interface EventsSignature { [key: ...

Exploring the SOLID Design Principles through TypeScript

Recently, I came across an intriguing article discussing the SOLID principles and delving into the concept of the Dependency Inversion Principle (DIP). The article presented an example to illustrate this principle using both an incorrect and a correct appr ...

Having difficulty creating a custom user registration field in Services 3.0 for Drupal

On attempting to submit data to my custom zip code field on the user registration form, I encounter the following issue: Sending post data to endpoint/user/register.json { "name":"testuser123", "pass":"testuser123", "mail":"<a href="/cdn-cgi/l/email-p ...