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

Encountering a 404 error while attempting to utilize ng2-charts

I am encountering an issue while attempting to integrate ng2-charts. Despite going through numerous similar threads on GitHub and other platforms, I have yet to find a solution. The error message I am receiving is as follows: Error: (SystemJS) XHR error ( ...

Angular: Observing DOM changes through observables

I have been exploring ways to track changes in the DOM of my angular component. Utilizing observables to capture those changes into a typescript variable, although uncertain if that's the right approach. Here is how I've set it up: app.componen ...

Transform a series of combined Longitudes and Latitudes into separate arrays - one for Longitude and one for Latitude

Here's a sample of longitude and latitude values for a polygon: [ [ 51.11041991029261, -2.274169921875 ], [ 51.08282186160978, -3.460693359375 ], [ 50.443513052458044, -3.570556640625 ], [ 50.443513052458044, -1.966552734375 ] ] I am trying to extra ...

Validating Emoji Inputs in Angular

Is there a way to validate input for Emoji and display an error message if invalid? The form field in question is: 'name': new FormControl('', [Validators.required]), ...

PHP code to transfer a set number of random values from one array to another

I'm facing an issue while trying to transfer 5 random values from one array to another using the code below. The problem I'm encountering is that only 3 or 4 values are successfully copied, while the rest (1 or 2) end up being assigned as null. I ...

Choosing a single element through viewChild using the "#" selector in Angular 2

Is there a special method to choose multiple tags on the same level with the same tag? <div #el></div> <div #el></div> <div #el></div> I keep getting an error message that says "Reference "#el" is defined several times ...

Modify capital letters to dashed format in the ToJSON method in Nest JS

I am working with a method that looks like this: @Entity() export class Picklist extends BaseD2CEntity { @ApiHideProperty() @PrimaryGeneratedColumn() id: number; @Column({ name: 'picklist_name' }) @IsString() @ApiProperty({ type: Str ...

Unlocking keys of JavaScript class prior to class initialization

My constructor was becoming too large and difficult to maintain, so I came up with a solution to start refactoring it. However, even this new approach seemed bulky and prone to errors. constructor(data: Partial<BusinessConfiguration>) { if(!d ...

Ensuring type safety at runtime in TypeScript

While delving into the concept of type safety in Typescript, I encountered an interesting scenario involving the following function: function test(x: number){ console.log(typeof x); } When calling this method as test('1'), a compile time er ...

Instead of relying on the valueChanges method, consider using setValue or patchValue in Angular 4 to monitor

I've implemented a floating point directive on fields in a reactive form to enhance readability by adding commas every 1000 and appending .00 to field values. This formatting works well, with onBlur triggering the formatting and onFocus removing it. ...

In React-Native, implement a function that updates one state based on changes in another state

I need to trigger a function when a specific state changes. However, I encountered the error 'maximum update depth reached'. This seems illogical as the function should only respond to changes from stateA to update stateB. I attempted using setSt ...

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...

Controlling the visibility of an element in Angular2 by toggling it based on an event triggered by a

Within my component, there is a child element: <fb-customer-list (inSearchMode)="listIsInSearchMode = event$"></fb-customer-list> This child element emits an event that contains a boolean value to indicate when it changes modes. In the paren ...

Tips for generating a list in Angular2 based on previous selections

import { Component } from '@angular/core'; export class Superhero { name: string; } const SUPERHEROES: Superhero[] = [ { name: 'GK-1' }, { name: 'GK-2' }, { name: 'GK-3' }, { name: 'GK-4&ap ...

Tips for Logging HTTP Communication Errors in Angular

When making an HTTP put call to update a record in my .Net MVC application, I have noticed that the controller's put logic is not being triggered as expected compared to other types of HTTP requests. I want to implement error handling by using the Ha ...

IE11 is throwing an error due to an unexpected quantifier in the regular expression

I have a string like SHM{GHT} and I need to extract the value from within the curly braces (GHT in this case). I used RegExp successfully to do this, but encountered an issue when testing on Internet Explorer. The page broke and I received an error message ...

My previously functioning TypeScript code suddenly ceased to work after I ran the yarn install command

Everything was running smoothly with my TypeScript code, both locally and on the server. However, after restarting the production code, I encountered errors (which required me to reinstall packages with yarn install). Strangely enough, when I try to yarn i ...

Troubleshooting an angular problem with setting up a dynamic slideshow

I am currently working on building a slideshow using plain HTML, CSS, and JavaScript. I referred to the following example for guidance: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto However, despite implementing the code prov ...

Arranging a collection of objects (Displaying information in a random sequence)

Here is a summary of the data returned in a shortened version: var array = [{ "response": { "itineraries":[ { "price": { "totalPricePerPassenger":"104" ...

Produce new lines of code using the vscode.window.activeTextEditor.edit method in Visual Studio Code

Hey everyone, I'm currently working on a vscode extension that can automatically generate template code based on the language you are using when you click a button. However, there seems to be an issue with the formatting of the generated code as it do ...