Angular Material Table displaying real-time information

Recently, I've delved into Angular and have been experimenting with creating a dynamic table to showcase data.

Currently, I have managed to get it partially working with static data.

I drew inspiration from this particular example: https://stackblitz.com/angular/lrpjroljdly?embed=1&file=app/table-selection-example.html

const COLUMN_DATA: IClusterColumnOrient[] = [...Array(10).keys()].map((_, index) =>({
      columnName: (Math.random() + 1).toString(36).substring(7),
      schemaName: (Math.random() + 1).toString(36).substring(7),
      columnType: (Math.random() + 1).toString(36).substring(7),
      id: (Math.random() + 1).toString(36).substring(7),
      tableName: (Math.random() + 1).toString(36).substring(7),
      databaseName: (Math.random() + 1).toString(36).substring(7),
      databaseId: (Math.random() + 1).toString(36).substring(7)
}))




@Component({
  selector: 'column-search',
  templateUrl: './column-search.component.html',
  styleUrls: ['./column-search.component.scss'],
})


export class ColumnSearchComponent implements OnInit{

  displayedColumns: string[] = ['select', 'columnName', 'columnType', 'tableName', 'schemaName'];

  selection = new SelectionModel<IClusterColumnOrient>(true, []);
  @ViewChild('searchInput', { static: true }) searchInput: ElementRef;
  columnsData: IClusterColumnOrient[]
  isSearching: boolean 
  columns: string[]
  dataSource = new MatTableDataSource<IClusterColumnOrient>(COLUMN_DATA);

While this setup works effectively, when attempting to switch out the COLUMN_DATA with this.columnData for dynamic data, an error surfaces:

Property 'columnsData' is used before its initialization.

How can I successfully substitute this with dynamic data?

Answer №1

When encountering this error message, it is important to pay attention to the clues it provides. The issue lies in declaring the property

columnsData: IClusterColumnOrient[]
without initializing it. Although you initialize this variable within your constructor, when you create the MatTableDataSource, it remains uninitialized and only declared. To rectify this, ensure you declare the data source as done with the columnsData property.

dataSource: MatTableDataSource<IClusterColumnOrient>;

Subsequently, move the initialization of your datasource inside the constructor to prevent this problem from occurring.

constructor(private httpClient: HttpClient){
    this.isSearching = false
    this.columnsData = []
    this.dataSource = new MatTableDataSource<IClusterColumnOrient>(this.columnsData);
  }

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

Expanding material UI theme choices through module augmentation is currently ineffective with TypeText

For those experiencing the issue, a codesandbox has been provided for convenience. Click here to access the codesandbox. Curiously, the TypeText feature is not functioning properly while the SimplePaletteColorOptions is working as expected. Despite being ...

What are some creative ways to format text displayed using ngx-markdown?

I'm currently in the process of building a blog using Angular and I have decided to use Markdown for creating my posts. Specifically, I am looking into integrating ngx-markdown for rendering purposes. As of now, I am developing a component dedicated t ...

Passing parameters to an Angular CLI ejected app

Currently, I am utilizing @angular/[email protected]. I have leveraged the new eject feature to modify the webpack configuration. Now, I find myself perplexed on how to pass parameters to my build process. For instance, how can I execute ng build --p ...

displaying a pair of inputs next to each other

Is it possible to display two input fields side by side? I am using Angular's matInput forms, but struggling to position the second input next to the first. What I would like to achieve is to have "input1 , input2" on the same line. Here is my code: ...

Dissimilarities in behavior between Angular 2 AOT errors

While working on my angular 2 project with angular-cli, I am facing an issue. Locally, when I build it for production using ng build --prod --aot, there are no problems. However, when the project is built on the server, I encounter the following errors: . ...

How can I incorporate MS Teams call recording into my web platform?

Currently in the process of developing a web application using Angular. Successfully integrated video call functionality through Azure Communication. Looking to now incorporate MS Teams call recording feature. Seeking assistance with reference links and s ...

Creating a TypeScript shell command that can be installed globally and used portably

I am looking to create a command-line tool using TypeScript that can be accessed in the system's $PATH once installed. Here are my criteria: I should be able to run and test it from the project directory (e.g., yarn command, npm run command) It must ...

Enhancing TypeScript Types with a custom method within an Angular 2 context

I am working on an Angular 2 project using the CLI. Currently, I am trying to add a custom method to the String type as shown below. interface String { customMethod(): number; } String.prototype.customMethod = function() { return 0; } Despite my ...

Having trouble uploading a PNG image (logo) with Cypress

I have been attempting to upload a png file using Cypress and here is what I have tried so far: Cypress.Commands.add('upload_image', (fileName, selector) => { return cy.get(selector).then(subject => { return cy.fixture(fileName, &apo ...

An issue has been detected in the @angular/material/autocomplete/typings/autocomplete-origin.d.ts file: The type 'ElementRef' is not declared as a generic type

Recently, I downloaded an Angular template that utilizes the Angular Material library. While trying to run this template on my local machine, I successfully executed the npm install command. However, when attempting to run ng serve, I encountered several w ...

Do I have to wait for the HTTP get request to access the fetched object property?

I am currently working with Angular and TypeScript on a dish-detail component that is accessed through 'dishes/:id' The dish object returned has a property called components, which contains an array of objects with two properties: id: type stri ...

Starting a new subscription once the current one expires

What is the process for starting a new subscription once an existing one ends using rxjs operators in Angular with 2 select statements? this.store.pipe( takeUntil(this.onDestroy$), select(getDatasetIsCreation), filter((datasetCreation) ...

Unable to find any routes that match child routes using the new Angular 2 RC1 router

ApplicationComponent import { Component } from '@angular/core'; import {Router, ROUTER_DIRECTIVES, Routes, ROUTER_PROVIDERS} from '@angular/router'; import {SchoolyearsComponent} from "./schoolyear/schoolyears.component"; @Component({ ...

Test Transmission Service

Hey there, I'm currently working on writing Angular code for a component that involves an observable. However, I'm facing some issues testing the broadcast service as I keep getting an error indicating that the service is not being called. Does a ...

Creating a unique type with a suffix of `px`

Understanding how to create a Position type class is clear: class Position { x: number = 0; y: number = 0; } However, I now require the x and y values to be integers with the suffix of px, like this: const position = { x: '1px', y: &ap ...

How can I use appendChild to place two different elements into a single div?

While exploring similar questions on this topic, I have unfortunately not come across a solution that works for me. My challenge is trying to insert two a elements inside of a newly created div element using appendChild. However, I am unable to append them ...

Have the quantities in the orderState been recently updated?

Whenever I modify the quantity of an order item, does it result in creating a duplicate entry for that particular item in the state every time? For instance, if the action.payload.indexNumber is 2 and action.payload.quantity is set to 100. This snippet s ...

Delete local data storage in Angular 2 upon closing the window

After the user logs in, I store their token in local storage so that it is accessible across all tabs. However, I need to remove this token from local storage when the user closes the browser or window. What is the best way to clear local storage upon clo ...

Linking a string value to a specific data structure in TypeScript

I'm currently exploring typescript and I have a question about mapping a string value to a custom type when using templates in function calls. For instance: object.method<TypeMapper['CustomType']>([...]) In this scenario, 'Cust ...

How do I create a standalone .ts file with Angular 9?

Just diving into Angular development and eager to create a standalone .ts file without having to generate an entire component. Can anyone guide me on how to achieve this using ng generate? Scenario: During the application build process, I need to write th ...