Utilizing a fixed array as the data source for a mat-table

I am currently working on implementing the Angular Material table into my project. I am encountering an issue when trying to define the [dataSource]="data", even though I am using code similar to the examples provided.

My question may seem basic, but my table data is just a simple array of objects. How can I successfully integrate this?

For illustration purposes, let's consider that my data is structured like this:

public data = [{ ID: 1, Code: "Hi" }, { ID: 2, Code: "Bye" }];

Below is the current code I am using:

<div class="example-container mat-elevation-z8">
    <mat-table #table [dataSource]="data">
        <ng-container matColumnDef="number">
            <mat-header-cell *matHeaderCellDef> Number </mat-header-cell>
            <mat-cell *matCellDef="let row"> {{ row.ID }} </mat-cell>
        </ng-container>

        <ng-container matColumnDef="Code">
            <mat-header-cell *matHeaderCellDef> Code </mat-header-cell>
            <mat-cell *matCellDef="let row">{{row.Code}}</mat-cell>
        </ng-container>

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

Answer №1

The resources provided for understanding the Angular Material Table were somewhat lacking in clarity. I believe I can offer a more concise explanation of the examples presented.

<mat-table [dataSource]=”data”>
  ...
</mat-table>
  • [dataSource]=”data”: This corresponds to your data array containing the information you wish to display. In this case, it is simply referred to as 'data'.
  • There is no need to create a new DataSource instance as suggested in Pierre Mallet's response; using an array will suffice. However, if you choose to do so, the most straightforward approach would be (based on the example provided):

    public dataSource = new MatTableDataSource(this.data);

    • The advantages of utilizing/extending the DataSource type are outlined here in the documentation.
<ng-container matColumnDef="userName">
  <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
  <mat-cell *matCellDef="let user"> {{user.name}} </mat-cell>
</ng-container>
  • matColumnDef="userName": This serves as a distinctive identifier for this ng-container. Note that there are no [] around 'matColumnDef', indicating that this is not a binding. The name chosen has no relation to the displayed data and may be customized as needed.

  • <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
    : This section is fairly straightforward. Replace 'Name' with any desired string that should appear at the top of the column.

  • The sequence of ng-containers does not impact their display order. Furthermore, defining these ng-containers here does not guarantee their display; visibility and order are determined later with *matHeaderRowDef.

  • <mat-cell *matCellDef="let user"> {{user.name}} </mat-cell>
    : Here, you specify the data displayed within this column. The variable 'user' is defined h̲e̲r̲e̲ and is not directly linked to your dataset. You have the flexibility to assign any name to this variable, but the property referenced ('name') must exist in the bound datasource.

<mat-header-row *matHeaderRowDef="columnsToDisplay"></mat-header-row>

  • *matHeaderRowDef="columnsToDisplay"
    : This determines which ng-container headers will be exhibited. 'columnsToDisplay' is an array of strings corresponding to the identifiers assigned to the ng-containers. The order of identifiers within this array dictates the appearance sequence of column headers. Omitting an identifier from the array results in its exclusion from the display.

<mat-row *matRowDef="let myRowData; columns: columnsToDisplay"></mat-row>

  • This code renders the rows within the specified columns. With the exception of 'columnsToDisplay', variables are declared in this section.

Answer №2

Even if you opt for static data, you will still need to create a new DataSource.

When using mat-table, a real DataSource is always required in the @Input. Since DataSource is an abstract class, you must create a class that inherits from it.

This custom DataSource class must have a "connect" method implemented, which should return an Observable containing the data you want to display.

In your scenario, something like this should work:

// In your component

interface MyDataType {
    ID: number;
    Code: string;
}

export class StaticDataSource extends DataSource<MyDataType> {
  constructor(private staticData: MyDataType[]) {
    super();
  }

  connect(): Observable<MyDataType[]> {
    return Observable.of(this.staticData);
  }

  disconnect() {}
}
...
this.staticDataSource = new StaticDataSource(data);

// In your template
 <mat-table #table [dataSource]="staticDataSource">

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

Ways to simulate a service using get() method with a particular data structure

https://i.sstatic.net/zc7bu.pngI've been working on writing unit tests for my component and simulating a service that makes HTTP requests. The response data structure looks like this: { ContactActivityView :[ { Code:"AB", ...

What is the best way to extract accurate information from an observable?

I'm having trouble retrieving the correct data from an observable in my project. Here is the code for my API call: getLastxScans(amount: number): Observable<Scan[]> { return this.http.get<Scan[]>(`${this.ROOT_URL}/Scan/amount/${amo ...

The Angular service successfully provides a value, yet it fails to appear on the webpage

Currently, I am starting to dive into Angular from the ground up. One of my recent tasks involved creating a component called 'mylink' along with a corresponding service. In my attempt to retrieve a string value from the service using 'obse ...

Tips on handling multiple Redux toolkit CreateApi interceptors

I came across this solution here for implementing a reAuth baseQuery in Redux Toolkit. I have several backend services that all use the same refresh token concept. Is there a way to create a single baseQueryAuth function that can be used by multiple creat ...

Angular (15) Encountering difficulties in expanding a typed FormGroup

Currently, I am experimenting with typed FormGroup. This is what I have created so far: export interface CustomFormControls { name: FormControl<string|null> content: FormControl<string|null> } export class CustomForm extends FormGroup< ...

How can I bypass additional ngIf checks in the Angular template if a variable is null?

I have this code snippet in my template: <div class="icon-action" *ngIf="node == null ? false : node.data && node.data.name && !node.parent.data.virtual" (click)="delete(node)"> ...

What are the steps for setting up Angular and Rails on Nginx for deployment

I have a challenge with setting up my NGINX server. I am hosting both the Angular and Rails servers on the same instance and need guidance on how to make them work harmoniously on the same server. Here's what I've done so far: NGINX configurat ...

A section of the URL path has been deleted, leading to a repetitive cycle of clicking back and forth in

While using the navigate function of Router in angular, I encountered a strange issue. It seems that when I navigate once, it actually creates two navigations in history. Additionally, the URL is automatically updated with part of the URL being stripped of ...

Maintaining accurate type-hinting with Typescript's external modules

Before I ask my question, I want to mention that I am utilizing Intellij IDEA. In reference to this inquiry: How do you prevent naming conflicts when external typescript modules do not have a module name? Imagine I have two Rectangle classes in different ...

Tips on personalizing the FirebaseUI- Web theme

Can someone help me find a way to customize the logo and colors in this code snippet? I've only come across solutions for Android so far. if (process.browser) { const firebaseui = require('firebaseui') console.log(firebaseui) ...

Creating a custom design for ng-bootstrap accordion using CSS styling

I've encountered an issue with my Angular 2 component that utilizes an accordion from ng-bootstrap. While the functionality works perfectly, I'm facing a problem with applying custom styles using the .card, .card-header, and .card-block classes o ...

Ensure that the background view remains interactive while adding an overlay on top for an enhanced user experience

Hey everyone, I could use some help with a question I have. My issue is that I am struggling to figure out how to make two views overlap while still allowing the background view to be interactive. Currently, I am using absolute positioning for the foregr ...

If a component does not have a specified return type annotation, it will default to an 'any' return type

I'm struggling to understand the typescript error that keeps popping up, it says: 'MyGoogleLogin', which doesn't have a return-type annotation, is being given an implicit 'any' return type. All I want is for the component t ...

Having trouble with my React component timer not functioning properly

How can I utilize the Header Component as a Clock timer for my webpage to update every second? Despite searching on Google, I couldn't find examples that match my requirements. Why is the tick() function not functioning properly even though there are ...

Tips for organizing and controlling various segments of your Angular 2 application

I am working with a specific template and I want to organize my application using ASP.NET Areas. Let's consider a website that has a public area and an admin area. Currently, I can display the home area without any issues, but I am unsure about how to ...

Is it possible to create a distinctive property value within an ngFor loop that operates autonomously across two child components?

I am working on a functionality where, upon clicking on a specific car brand, the name of the person and their favorite car will be displayed at the bottom. However, I'm facing an issue where the car brand is being repeated among all items in the ngFo ...

Having trouble applying CSS while printing using the ngx-print library in Angular 14. Can anyone help me out with this issue

The table shown in the image is experiencing issues with applying CSS properties when printing. While the background graphics feature has been enabled, the preview section still does not reflect the CSS styling. What could be causing this discrepancy? Cli ...

Exploring the world of third-party APIs

I am currently working on fetching data from an external API and displaying it. In order to enhance flexibility, I am aiming to completely separate the API integration from my code and use custom-defined data structures instead. Here is a brief visual ov ...

When utilizing <number | null> or <number | undefined> within computed() or signals(), it may not function properly if the value is 0

I've encountered an issue while implementing signals and computed in my new Angular project. There's a computed value that holds an id, which is initially not set and will be assigned by user interaction. To handle this initial state, I attempte ...

Guide on categorizing MUI icon types

My current code snippet is as follows: type MenuItem = { key: string; order: number; text: string; icon: typeof SvgIcon; }; However, when I attempt to use it in my JSX like this: <List> {MENU.map((menuItem: MenuItem) => ( ...