Presenting information using mat-table in Angular 2

Everything seems to be working fine with the code as I am able to display the data in mat-cards successfully. However, when I try to display it in mat-tables, I encounter index errors. I have made sure to import matTableDataSource, DataSource, CdkTableModule, and MatTableModule as well.

Component.ts

export class DriversComponent {
constructor(private webService : WebService, private route: ActivatedRoute, private auth: AuthService) {}
ngOnInit(){
    var name = this.route.snapshot.params['name'];
    this.webService.getDrivers(name);
    this.webService.getUser().subscribe();
    let dataSource = this.webService.getDrivers(name);
    let displayedColumns = ['id','name','lastname'];
}

Component.html

<div *ngFor="let driver of webService.drivers | async">
    <mat-table #table [dataSource]="dataSource" [@movePanel]='state'>
        <ng-container matColumnDef="id">
            <mat-header-cell *matHeaderCellDef>ID</mat-header-cell>
            <mat-cell *matCellDef="let lesson">{{driver.employeeId}}</mat-cell>
        </ng-container>
        <ng-container matColumnDef="name">
            <mat-header-cell *matHeaderCellDef>First Name</mat-header-cell>
            <mat-cell *matCellDef="let lesson">{{driver.firstName}}</mat-cell>
        </ng-container>
        <ng-container matColumnDef="lastname">
            <mat-header-cell *matHeaderCellDef>Last Name</mat-header-cell>
            <mat-cell *matCellDef="let lesson">{{driver.lastName}}</mat-cell>
        </ng-container>
        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
    </mat-table>
</div>

webservice.ts

private driverStore = [];
private driverSubjet = new Subject();
drivers = this.driverSubjet.asObservable();
constructor(private http: Http, private sb: MatSnackBar, private auth: AuthService) {
    this.getDrivers('');
}
getDrivers(user) {
    user = (user) ? '/history/' + user : '';
    this.http.get(this.BASE_URL + '/employee' + user).subscribe(response => {
        this.driverStore = response.json();
        this.driverSubjet.next(this.driverStore);
    }, error => {
        this.handleError("Unable to get drivers");
    });
}

Answer №1

To optimize your code, consider utilizing the lesson variable from your *matCellDef instead of relying on the driver variable within the *ngFor directive.

    <mat-table #table [dataSource]="dataSource" [@movePanel]='state'>
        <ng-container matColumnDef="id">
            <mat-header-cell *matHeaderCellDef>ID</mat-header-cell>
            <mat-cell *matCellDef="let lesson">{{lesson.employeeId}}</mat-cell>
        </ng-container>
        <ng-container matColumnDef="name">
            <mat-header-cell *matHeaderCellDef>First Name</mat-header-cell>
            <mat-cell *matCellDef="let lesson">{{lesson.firstName}}</mat-cell>
        </ng-container>
        <ng-container matColumnDef="lastname">
            <mat-header-cell *matHeaderCellDef>Last Name</mat-header-cell>
            <mat-cell *matCellDef="let lesson">{{lesson.lastName}}</mat-cell>
        </ng-container>
        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
    </mat-table>

Consider removing the *ngFor since the mat-table automatically displays data and only requires a data source to be provided.

Keep in mind that you may need to adjust the implementation of your getDrivers function as it currently does not return any value.

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

Jest may come across test suites, but it discreetly disregards the individual tests

Having encountered an issue with Jest testing in a Nuxt/Vue v2 project, I found that after making some changes, the tests were no longer running. The unit tests were either passing or failing initially, but suddenly stopped running altogether. ----------|- ...

Executing file upload in parent component with Angular 2

Is there a way to initiate a file upload from the parent component of the router? Specifically, I need to execute two functions located in the parent component - openFileSelect and uploadSelectedFile to manage the <input type="file"> element. This i ...

Retrieve the outermost shell of the VUEjs wrapper test-utils

While working on a VueJS test, I encountered an issue where accessing the outermost layer of HTML seemed impossible. No matter what methods I tried, the outermost layer was always ignored. Is there a way to gain access to this outermost layer so that I c ...

When attempting to display the image file path using the JavaScript API Notification in Angular, there is a challenge in

Hello fellow developers, I am currently facing an issue with retrieving a local image from my assets folder and displaying it on a new Notification object generated by the Web Notification API. I have an image in my assets folder with a .jpeg extension. ...

Using Angular 2, you can pass an object as a parameter to a function

Is there a way to pass an object as a parameter in the DOM on this forum? Within my HTML code, I have the following: <div class="list-items"> <ul> <li *ngFor="let i of item"> <span (click)="onAdd({{newUser.us ...

Two separate menus for each root file in Ionic 2

In my Ionic 2 project, I have developed two root files: app.component and report-menu. In order to make the report-menu module accessible in the app.component.module.ts file, I imported it successfully. However, I am facing an issue where one menu is dis ...

Tips for determining the defaultValue type in React.context usage

'use client'; import { useState, createContext, useMemo } from 'react'; type MessageStatus = 'default' | 'success' | 'error'; export type MessageProps = { type: MessageStatus; payload: string; }; ty ...

Utilizing event binding with ngForTemplate in Angular 2

Imagine having a straightforward list rendering component: import {Input, Component } from 'angular2/core' @Component({ selector: 'my-list', template: ` <div *ngFor='#item of items' (click)='onItemClicked(i ...

Leveraging the unique operator with an observable

I've been attempting to eliminate duplicates from my observable by using .distinct(), but it doesn't seem to be working as expected. There are no errors showing either... this.settingsService.getGuruQueries().subscribe(queries => { of<an ...

Tips for ensuring the angular FormArray is properly validated within mat-step by utilizing [stepControl] for every mat-step

When using Angular Material stepper, we can easily bind form controls with form groups like [stepControl]="myFormGroup". But how do we bind a FormArray inside a formGroup? Constructor constructor(private _fb: FormBuilder){} FormArray inside For ...

TypeScript Error: The Object prototype must be an Object or null, it cannot be undefined

Just recently, I delved into TypeScript and attempted to convert a JavaScript code to TypeScript while incorporating more object-oriented features. However, I encountered an issue when trying to execute it with cmd using the ns-node command. private usern ...

Angular not displaying retrieved data

Having an issue with fetching data from an API using Angular. Although the console log confirms that the data is successfully fetched, it doesn't display on the page. Any assistance would be greatly appreciated. Take a look at my code: app.component. ...

Using Angular2 Router can sometimes result in template "overwrites"

My routing implementation seems to be causing issues in my app. When I click the Login button, it should direct me to a new login page. However, instead of navigating away from the main page (VehicleComponent), it creates the login page within the main pag ...

Angular 10 Reactive Form - Controlling character limit in user input field

I'm currently developing an Angular 10 reactive form and I am looking for a way to restrict the maximum number of characters that a user can input into a specific field. Using the maxLength Validator doesn't prevent users from entering more chara ...

What is the best way to target changing elements displayed by *ngIf?

Trying to access a dynamic element generated by ngIf in the code below has proven to be challenging. I attempted two different methods: Using ElementRef and querySelector Component template: `<div class="test" *ngIf="expr"> <a id="b ...

Tips for crafting a test scenario for input alterations within Angular

Hello there, currently I am working on an application using Angular and TypeScript. Here is a snippet of my template code: <input type="text" placeholder="Search Results" (input)="searchInput($event)"> And here is the TypeScript code for the searc ...

Displaying an array object within an array of objects in Angular 2: A guide

Here is an example of a JSON file: { "id": 5, "url": "http://localhost:8000/api/v1/users/5/", "username": "Najmuddin", "email": "", "groups": [ { "id": 1, "url ": "http://localhost:8000/api/v1/groups/1/", ...

Oops! There seems to be an issue: Uncaught promise error - ReferenceError: google is not defined

I've integrated Angular 2 with Google Maps Places Autocomplete in my project, but I encountered an error: ERROR Error: Uncaught (in promise): ReferenceError: google is not defined Here's the HTML snippet: <agm-map id="googleMap"> ...

Utilizing Google Analytics 4 in a React TypeScript Environment

Currently, there are two options available: Universal Analytics and Google Analytics 4. The reasons why I lean towards using Google Analytics 4: Universal Analytics is set to be retired on July 1, 2023, so it makes sense to start fresh with Google Analyt ...

Unable to find solutions for all parameters needed by a CustomComponent within Angular

Whenever I attempt to compile the project for production, an error pops up: There is a problem resolving all parameters for EmployeeComponent in C:/.../src/app/employee/employee.component.ts: (?, ?, ?). Oddly enough, when I run the application, every ...