Link the Angular Material Table to a basic array

Currently facing a challenge with the Angular Material table implementation. Struggling to comprehend everything... I am looking to link my AngularApp with a robot that sends me information in a "datas" array. To display my array, I utilized the following code:

<table id="sensorsTable" class="table table-striped">
<tr *ngFor="let data of datas">
    <td>{{data.name}}</td>
    <td>{{data.value}}</td> 
</tr>
</table>

The above code was functioning well but now I aim to incorporate an Angular Material table.

Below is my TypeScript code and unfortunately my view does not update when the "datas" array changes...

If anyone can offer assistance, that would be greatly appreciated!

Here is the current TypeScript code:

import { Component } from '@angular/core';
declare var Robot: any;
import { HostListener } from '@angular/core';
import {DataSource} from '@angular/cdk/collections';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';

export interface Data {
  name: string;
  value: number
}

var datas: Data[] = [
  {name: 'Hydrogen', value: 1.0079},
  {name: 'Helium', value: 4.0026},
  {name: 'Lithium', value: 6.941},
  {name: 'Beryllium', value: 9.0122},
  {name: 'Boron', value: 10.811},
  {name: 'Carbon', value: 12.0107},
];

export class MyDataSource extends DataSource<any> {
  connect(): Observable<Data[]> {
    return Observable.of(datas);
  }

  disconnect() {}
}

@Component({
  selector: 'roomba-app',
  templateUrl: "./app.component.html",
  styles: ["./app.component.scss"]
}) 
export class AppComponent  { 
  datas: Array<Object> = [];
  robot:any;
  powerMotorRight: number;
  powerMotorLeft: number;
  maxSpeed = 200;

  displayedColumns = ['name', 'value'];
  dataSource = new MyDataSource();

  @HostListener('document:keypress', ['$event'])
  handleKeyPressed(event: KeyboardEvent) {
    let keyPressed = event.key;
    if(keyPressed == "z"){
      this.powerMotorRight = this.maxSpeed;
      this.powerMotorLeft = this.maxSpeed;
    }
    // Similar if statements for other key presses
  
        
  constructor(){
    let testData = {
      name: "test",
      value: "255"
    };
    this.datas.push(testData);

    this.robot = new Robot();

    
    this.robot.on("connected", function(){
        console.log("connected");
        this.robot.safeMode();
        this.robot.streamAllSensors();
  
     }.bind(this));

     
    this.robot.on("datas", function(receivedDatas:any){
        this.datas = receivedDatas;
        datas = this.datas;    
    }.bind(this));
  }
}

Answer №1

Give this a shot:

<tr *ngFor="let info of infos | async">

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

Manipulating a 2D array in Javascript and Jquery: Implementing push functionality

I am trying to set up an array structure as follows: track[divID][wrapID] However, when I attempted track[divID][wrapID] = wrapID, I encountered an issue. This is because I need to add more elements to the second dimension in another loop, like this: tr ...

Issue with Declarations in component's module causing functionality to not work as expected

After extensive searching, I couldn't find a solution to this particular issue. Here's the problem: As a beginner working on an Angular project for practice, I have a module named "AppMaterialModule" where I consolidate all Angular material comp ...

What is the best way to empty an input field after adding an item to an array?

In my Angular 2 example, I have created a simple functionality where users can add items to an array. When the user types something and clicks the button, the input is added to the array and displayed in a list. I am currently encountering two issues: 1 ...

What method can be used to fetch generic type parameter in typescript?

I am having trouble finding the type of E within the code provided below. class A<E> { getParameterType() { // I need to determine the type of E } } class B { } ** Example ** new A<number>().getParameterType() // number new A<B&g ...

Error: Angular encountered an undefined variable when attempting to import 'node_modules/bootstrap/scss/grid'

Having some trouble setting up Angular with SCSS and Bootstrap. When attempting to run ng serve, I encountered the following error: ./src/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: Undefined variable. ...

Angular is unable to iterate through a collection of ElementRef instances

My list of ElementRef contains all my inputs, but adding listeners to them seems to indicate that textInputs is empty even though it's not. @ViewChildren('text_input') textInputs!: QueryList<ElementRef>; ngAfterViewInit(): void { ...

Encountering errors during 'npm i' - issues arising from unresolved dependency tree

Recently, I have been facing issues with running npm i as it keeps failing and showing an error. The project is using Angular 15 without any previous errors, so it's puzzling why there is suddenly a complaint about Angular 16. npm ERR! code ERESOLVE n ...

Just starting out with Ruby and hitting a roadblock with Diagonal Difference

Currently working on a coding challenge from HackerRank called Diagonal Difference. This is the code I've written so far: def diagonalDifference(arr) first = 0 second = 0 i=0 puts arr while i < arr.length first += arr[i][i] ...

What is the procedure for entering the output generated by genMockFromModule when creating a custom mock in Jest?

Looking at my orders directory structure, I have a function in the orders/helpers file that I want to test using a manual Jest mock. orders __mocks__ helpers.ts __tests__ orders.ts helpers.ts orders.ts The orders/helpers.ts file contains ...

Array containing HTML code for Ionic framework

Just starting out with Ionic/Angular and I have a question. How can I display an array containing HTML content? { "code" : "06", "descr" : "Some text:</br>Other text.<br/>Other text</br>Other text." } When I try to print it, the HTML ta ...

Implement Stripe API mocking using Jest in Node.js with Typescript

I'm having trouble simulating the Stripe API for testing purposes. Although I don't have much experience with mocking functions using jest, I've already extensively researched how to mock the Stripe API without success. My file structure is ...

Get the @types definition installed from a forked repository

Background Information I recently made a workaround for a single type definition in my fork of DefinitelyTyped. This fix is located on a specific branch within my fork. It's important to note that this fix is temporary and should not be merged back ...

Exploring the ambiguity of explicit types with type generics

I am facing a type error issue with a Higher-Order Component (HOC): Error: Type 'number[]' is not assignable to type 'string'. Here is how I set up my HOC: const ComponentPage = renderPage(Component); However, I encounter the error ...

Exploring Angular: A Comparison of AfterViewInit() and AfterContentInit()

I am trying to understand exactly what triggers the AfterViewInit() and AfterContentInit() life-cycle hooks. According to the Angular documentation, AfterViewInit() is called by Angular after it creates a component's child views. and for AfterCon ...

Navigating the update and deletion of master-detail relationships in JSON structures

We are receiving the JSON Data in the following format, $invoice_data = { "CONTACT_ID": "1", "INV_SERIAL_NO": "100", "NAME": "baby", "INV_DATE": "2018-06-27", ...

Transform several JSON files into a PHP array

I have a JSON file that contains multiple JSON objects. Here is an example: {"t":"abc-1","d":"2017-12-29 12:42:53"} {"t":"abc-2","d":"2017-12-29 12:43:05"} {"t":"abc-3","d":"2017-12-30 14:42:09"} {"t":"code-4","d":"2017-12-30 14:42:20"} I am trying to re ...

Using command line arguments in a Tauri project with a Next.js frontend

I am utilizing Tauri.JS in conjunction with Next.js. In this scenario, I need to execute the console command: npm run tauri dev --<argument name>=<some value>. Afterwards, I should be able to access the value of the argument in my JavaScript ...

Angular 8 ngFor not displaying expected information from object

I have a set of data which includes IDs, versions, and user details for Paul and Peter. See below: var data = { id: 1 version: 1 user: [ { name: 'paul' }, { name: 'peter' ...

Angular repeatedly triggering cloud function

Currently facing an issue in my angular project where a cloud function is being triggered multiple times. The console.log('call') statement is appearing three times. this.profileList$ = this.usersService.profileList(this.route.snapshot.paramMap.g ...

Stay Alert: Angular Observable Continuously Monitored for Promise Updates

I am currently working on an angular application that has a connection with a printer. The printer possesses its own status service that is implemented as a promise, providing the printer's current status as a response. However, I am facing an issue w ...