error with angular5 material table data source

I tried multiple solutions from Stack Overflow but none of them worked for my Angular 5 project using TypeScript. I'm attempting to replicate the "Data table with sorting, pagination, and filtering" example from here.

Although there are no errors, the data is not displaying in the table. Has anyone encountered and resolved this issue?

HTML:

<mat-form-field>
    <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>

<div class="mat-elevation-z8">
    <mat-table [dataSource]="dataSource" matSort>

        <!-- ID Column -->
        <ng-container matColumnDef="id">
            <th mat-header-cell *matHeaderCellDef mat-sort-header> ID </th>
            <td mat-cell *matCellDef="let row"> {{i['title']}}} </td>
        </ng-container>

        <!-- Progress Column -->
        <ng-container matColumnDef="progress">
            <th mat-header-cell *matHeaderCellDef mat-sort-header> Progress </th>
            <td mat-cell *matCellDef="let row"> {{row.progress}}% </td>
        </ng-container>

        <!-- Name Column -->
        <ng-container matColumnDef="name">
            <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
            <td mat-cell *matCellDef="let row"> {{row.name}} </td>
        </ng-container>

        <!-- Color Column -->
        <ng-container matColumnDef="color">
            <th mat-header-cell *matHeaderCellDef mat-sort-header> Color </th>
            <td mat-cell *matCellDef="let row" [style.color]="row.color"> {{row.color}} </td>
        </ng-container>

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

    <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</div>

component.ts

export interface UserData {
    id: string;
    name: string;
    progress: string;
    color: string;
}

/** Constants used to fill up our data base. */
const COLORS: string[] = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple',
                            'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray'];
const NAMES: string[] = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',
                            'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper',
                            'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'];

/**
* @title Data table with sorting, pagination, and filtering.
*/

export class TableOverviewExample implements OnInit {
    displayedColumns: string[] = ['id', 'name', 'progress', 'color'];
    dataSource: MatTableDataSource<UserData>;

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

    constructor() {
        // Create 100 users
        const users = Array.from({length: 100}, (_, k) => createNewUser(k + 1));

        // Assign the data to the data source for the table to render
        this.dataSource = new MatTableDataSource(users);
    }

    ngOnInit() {
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
    }

    applyFilter(filterValue: string) {
        this.dataSource.filter = filterValue.trim().toLowerCase();

        if (this.dataSource.paginator) {
            this.dataSource.paginator.firstPage();
        }
    }
}

/** Builds and returns a new User. */
function createNewUser(id: number): UserData {
    const name =
        NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +
        NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';

    return {
        id: id.toString(),
        name: name,
        progress: Math.round(Math.random() * 100).toString(),
        color: COLORS[Math.round(Math.random() * (COLORS.length - 1))]
    };
}

Answer №1

Your code will trigger an error. To fix it, simply replace the current code in the html file and Id column with {{row.id}}.

    <ng-container matColumnDef="id">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> ID </th>
        <td mat-cell *matCellDef="let row"> {{row.id}} </td>
    </ng-container>

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

The element is automatically assigned an 'any' type due to the inability to use a 'string' type expression to index the 'DataType' type

Encountering an issue where row[header.key] is displaying the error message Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'DataType'. I prefer not to use type:any and ...

Arranging containers by invoking a function with material UI

I am completely new to material UI, typescript, and react, so if I make any mistakes or use the wrong terms please feel free to correct me. My goal is to place 4 boxes on a page, with three of them in a row and the fourth stacked below the first box. Curr ...

Is there a way to expand the return type of a parent class's methods using an object

Currently, I am enhancing a class by adding a serialize method. My goal is for this new method to perform the same functionality as its parent class but with some additional keys added. export declare class Parent { serialize(): { x: number; ...

Exploring the use of a customizable decorator in Typescript for improved typing

Currently, I am in the process of creating TypeScript typings for a JavaScript library. One specific requirement is to define an optional callable decorator: @model class User {} @model() class User {} @model('User') class User {} I attempted ...

Mastering the art of shaping state in NGRX for the master-detail pattern

Imagine a scenario where I am developing a compact app for organizing tasks. This app makes use of angular and NGRX to efficiently manage the state. Each day, the user loads tasks in the morning and then travels to different locations to complete them. Th ...

Methods for populating an object with Interface type and returning it

This is my function that populates an object based on interface type: public _fillAddModel<T>(lessonId: number, studyPeriodId: number, confirmed: boolean = false): T { let data: T; data = { lesson: this.substitution.lessonNumber, ...

Angular2: PrimeNG - Error Retrieving Data (404 Not Found)

I'm facing an issue with using Dialog from the PrimeNG Module. The error message I keep getting is: Unhandled Promise rejection: (SystemJS) Error: XHR error (404 Not Found) loading http://localhost:4200/node_modules/primeng/primeng.js I followed the ...

Dynamically loading inter-component JS/TS in an Angular application

Hey there! I have a current component structure set up like this: appComponent --infoComponent ---beforeComponent ---afterComponent Both the before and after components have navbars with unique IDs, specifically navbar_before and navbar_after. H ...

Angular and Spring not cooperating with GET request. What's the issue?

I have been working on integrating a simple GET request to send an Object of type SearchMessage from my Spring Boot server to my Angular client application. After running the server application and verifying that the JSON content is correctly displayed at ...

Angular component showcasing the usage of a nested input-group

I have developed an input component and a datepicker component in Angular. The input component generates the appropriate input tag based on the type parameter, whether it's text, number, etc. Meanwhile, the date picker is another component that contai ...

I need to show the value of A$ in a React form input, but ensure that only the numerical value is

I'm currently facing an issue where I want to show the currency symbol A$ in an input field. <form [formGroup]="incomeForm" *ngFor="let field of incomeFields"> <mat-form-field fxFlex> <input matInput [value]="incomeForm ...

What is the syntax for assigning a public variable within a TypeScript function?

I am finding it challenging to assign a value to a public variable within another function. I seem to be stuck. export class MyClass{ myVar = false; myFunction(){ Module.anotherFunction(){ this.myVar = true; } } } ...

The Intersection Observer API is caught in a never-ending cycle of rendering

I am experimenting with the intersection observer API in order to selectively display elements in a CSS grid as the user scrolls, but I seem to have run into a problem of encountering an endless rendering loop. Below is the code snippet I am working with. ...

Real-time data not instantly stored using socket.io

In my current issue, whenever I receive a message with the action stop, I encounter a problem specifically with the setTotalScore function. Initially, the totalScore is set to 0, and upon receiving the message, it should update to match the user.score. How ...

Comparing dates in Angular 6 can be done by using a simple

Just starting with angular 6, I have a task of comparing two date inputs and finding the greatest one. input 1 : 2018-12-29T00:00:00 input 2 : Mon Dec 31 2018 00:00:00 GMT+0530 (India Standard Time) The input 1 is retrieved from MSSQL database and the in ...

Extract keys from a list of interface keys to create a sub-list based on the type of value

Issue Can the keys that map to a specified value type be extracted from a TypeScript interface treated as a map? For example, consider the WindowEventMap in lib.dom.d.ts... interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHan ...

Can you advise on how to generate a key to access an environment.ts value within a *ngFor loop? Specifically, I am trying to locate keys that follow the pattern 'environment.{{region}}_couche_url' within the loop

I currently have a block of HTML code that is repeated multiple times. <!-- Metropolitan Map --> <div> <app-map [name] = "(( environment.metropole_name ))" [layer_url] = "(( environment.metropole_layer_url ))" ...

What is the best way to update a child component when a function is triggered by another child component?

In my questions-manager.component.html component, the structure looks like this: <div> <main> <div> <questions-component [title]="'title'" [id]="id" (changeStatus)="statusChang ...

Implementing an interface by assigning a type interface to a class instance with additional properties

Just to clarify my question, let me provide more details. Let's say I have a class called MyClass that implements an interface named MyInterface. Besides the properties required for the implementation (such as myProp1), it also includes an additional ...

What is the best way to link the value of a mat-slider to an input field in a reactive form?

Is there a way to synchronize the min and max values of a ranged mat-slider with corresponding input fields? Currently, when I set numbers in the input fields, the slider updates correctly. However, when I use the slider to change the value of the input fi ...