What is the process for inserting a column into a Mat Table in Angular?

I am attempting to insert a new column into a mat table, but the column is showing up with multiple names.

HTML FILE

<div class="main-content">
    <form class="example-form">
        <mat-form-field class="example-full-width">
            <input
                matInput
                [(ngModel)]="columnName"
                name="columnName"
                placeholder="Add Column Here"
            />
        </mat-form-field>

        <button
            mat-button
            mat-raised-button
            color="primary"
            (click)="addColumns()"
        >
            Add
        </button>

        <mat-table [dataSource]="columnDataSource">
            <ng-container
                *ngFor="let column of displayedColumns"
                [cdkColumnDef]="column"
            >
                <mat-header-cell *cdkHeaderCellDef>{{
                    displayedColumns
                }}</mat-header-cell>
                <mat-cell *cdkCellDef="let row">{{
                    displayedColumns
                }}</mat-cell>
            </ng-container>
            <mat-header-row
                *matHeaderRowDef="displayedColumns"
            ></mat-header-row>
            <!-- <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row> -->
        </mat-table>
    </form>
</div>

TS FILE

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material';

/**
 * @title Basic use of `<table mat-table>`
 */
@Component({
  selector: 'table-basic-example',
  styleUrls: ['table-basic-example.css'],
  templateUrl: 'table-basic-example.html',
})
export class TableBasicExample implements OnInit {
    displayedColumns = [];
    columnDataSource: any = [];
    columnName: any;
    constructor() {}
    addColumns() {
        this.displayedColumns.push(this.columnName);
        this.columnDataSource = new MatTableDataSource<any>(
            this.displayedColumns
        );
        console.log(this.displayedColumns);
    }

    ngOnInit() {}
}

When trying to add a column to the mat table, I have encountered an issue where the column name is being duplicated. You can view my code on StackBlitz here: https://stackblitz.com/edit/add-extra-column-mat-tabe?file=app%2Ftable-basic-example.ts

Answer №1

Make a modification on line 27 by replacing the following content:

<mat-header-cell *cdkHeaderCellDef>{{ displayedColumns }}</mat-header-cell>

With:

<mat-header-cell *cdkHeaderCellDef>{{ column }}</mat-header-cell>

Answer №2

The reason for the display of all values is because the displayedColumns is being shown entirely:

<mat-header-cell *cdkHeaderCellDef>{{displayedColumns}}</mat-header-cell>

Within your ng-container, the data is looped through using ngFor:

<ng-container *ngFor="let column of displayedColumns" [cdkColumnDef]="column">

To rectify this, modify the mat-header-cell to show each individual item, in this case 'column'. The updated mat-header-cell code should be as follows:

<mat-header-cell *cdkHeaderCellDef>{{column}}</mat-header-cell>

This adjustment ensures that each item is looped through individually instead of displaying the entire array each time.

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

Utilize ng-content to access the component provider within a child component

I have been utilizing the ngx-mapbox-gl library, found at this link. This library includes a component called "mgl-map", which allows users to add child layer components that will render on the map. My objective is to create a parent component that contai ...

How to center scroll overflowed div vertically on element using Angular (5)

I have created a unique table layout using divs and the flex property with Angular. Here is an example of how it looks: <div class="tbody"> <div class="tr" *ngFor="let ask of asks"> <div class="td centered red">{{ask.price | ...

Service in Angular 2 is encountering issues when attempting to resolve all parameters

I'm facing an issue with injecting UserService into LoginService in my application. Whenever I try to do so, the app fails to run properly. The console displays the following error: Error: Can't resolve all parameters for UserService: ([objec ...

Condition for rendering child components using Angular guard

I am faced with a scenario where I have 3 children in a parent component and I need to render them based on specific conditions: If my variable is equal to zero, the welcomePage should be rendered If the variable falls between one and ten, then the interm ...

What is the process for refreshing the component content in Angular 2?

There was a moment during execution when my URL had the following appearance: http://localhost:4200/personal/51c50594-a95c-4a18-ac7b-b0521d67af96 I desire to visit a page with a different GUID and different content. http://localhost:4200/personal/{other ...

What is the best way to designate external dependencies in WebPack that are not imported using '*'?

I need assistance with specifying office-ui-fabric-react as an external dependency in my TypeScript project using Webpack. Currently, I am importing only the modules I require in my project: import { Dialog, DialogType, DialogFooter } from 'office-u ...

Update the checkbox value to a string

I have come across many questions regarding changing the value of a checkbox to a string, but I am still facing difficulties. Specifically, I need to change the value from true - false to 'A' - 'B'. My code is based on reactive forms in ...

What is the best way to identify the initial item in an array that is also present in a different array through TypeScript?

I have two arrays of objects and I only want to retrieve the first matching object from one array if it is found in the other array. I need to stop the search after finding the first match, but I am having trouble breaking out of the loop. Example 1:- var ...

Can you customize the "rem" values for individual Web Components when using Angular 2's ViewEncapsulation.Native feature?

I'm interested in creating a component with ViewEncapsulation.Native that utilizes Bootstrap 4 while others are using Bootstrap 3. Below is the component code with Bootstrap 4: import { Component, ViewEncapsulation } from '@angular/core'; i ...

The code snippet for the React TypeScript Cheatsheet in the Portal sample appears to be malfunction

I have implemented a strict version of TypeScript and ESLint in my project. The code for this portal was originally sourced from the documentation available here: After making some modifications, the code now looks like this: import React, { useEffect, u ...

I have encountered an issue while utilizing dynamic form functionality in Angular 7. The error message displayed is: "Error: Cannot find control with name: 'i'"

While working with Angular 7 dynamic forms, I encountered an error that I'm struggling to resolve. As a newcomer to Angular, this has been quite challenging for me. import { Component } from '@angular/core'; import {FormBuilder, FormArray} ...

What is the method for bypassing tests in TypeScript/esrun when utilizing the node native test runner?

I have been utilizing the node test runner for my testing purposes. Within a small demo file, I have included some tests: import { describe, test } from "node:test"; import assert from "node:assert"; describe("thing", () => ...

Unable to append element to array in TypeScript/Angular

Programming Environment: Angular 6 export class Student { fullName: string; age: number; classType: string; } export class MyClass { public resultData: Array<Student> = []; processedData = { studentData: [ { ...

Is there a way to automatically scroll 50 pixels down the page after pressing a button?

Is there a way to make my page scroll down in Angular when a button is clicked? I attempted to use this code, but it didn't have the desired effect. What is the best method for scrolling the page down by 50px? window.scrollBy(0, 50); ...

How to initiate focus on Angular 2 MdInputContainer after the view has been

I am encountering an issue with setting focus on the first md-input-container element within a component when the view loads. Despite implementing a @ViewChild property and calling focus on it in the ngAfterViewInit method, the focus does not seem to be wo ...

Sending a POST request in my Angular 11 application is no problem, but I am curious about how to retrieve data specifically for a certain input value

question-task.image **verify if the image question is included** <form #postForm="ngForm" (ngSubmit)="onCreatePost(postForm.value)"> <div class="form-group"> <label for="title">Ti ...

Creating getter and setter functions for an input field model property in Angular

I need help creating getter and setter methods for an input field property. Here is my attempted code: import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', st ...

Is the package.json file properly structured with the required dependencies?

Just getting started with Angular 2 and I'm still getting the hang of the package.json file. I've run into some issues with imports. Upon reviewing my files, I noticed that I have both @angular and angular2 in my dependencies. Is this package.j ...

Guide to dynamically loading separate components on a single page in Angular 9

Rendering all components or widgets on the page at once can slow down the application's loading time. I prefer to have app-sidebar1, app-body, and app-sidebar2 load onto the DOM sequentially based on priority, rather than waiting for all components t ...

Utilize the nests cli swagger plugin to enable compatibility with external models

Exploring the functionality of the swagger plugin provided by nestjs, I am eager to try it out. While it works smoothly when defining a class like CreateUserDto, my goal is to incorporate types from a third-party library - specifically @adyen/api-library. ...