How do I retrieve the data returned from the component.ts file in Angular Material's MatTableModule when it is not directly inside the mat-table in the template?

I'm currently working on an Angular 5 project where I have integrated a table to display data using MatTableModule from angular material. This specific inquiry consists of two parts.

Within my project, there is a service that sends a GET request to the API and retrieves all the necessary data. The handling of this data occurs in the component.ts file mentioned below. Although this operation runs smoothly, the issue arises when viewing the table on smaller screens due to its lack of responsiveness. Consequently, I aim to iterate through the received data and exhibit it in an alternate format tailor-made for compact screens. Unfortunately, I am encountering hurdles while attempting to carry out this task.

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { DataSource } from '@angular/cdk/collections';
import { RoutesService } from '../../services/routes/routes.service';
import { Routes } from '../../services/models/routes.model';

@Component({...})
export class RoutesComponent implements OnInit {

  public displayedColumns = ['from', 'to', 'departures', 'duration', 'price'];
  public dataSource = new RoutesDataSource(this.routesService);

  constructor(private routesService: RoutesService) { }

  ngOnInit() { }
}

export class RoutesDataSource extends DataSource<any> {
  public iterable: string[] = ["foo", "bar"];
  
  constructor(private routes: RoutesService) {
    super();
  }

  connect(): Observable<Routes[]> {
    return this.routes.getRoutes();
  }

  disconnect() {}
}

In my template document:

<mat-table [dataSource]="dataSource">
  <!-- From Column -->
  <ng-container matColumnDef="from">
    <mat-header-cell *matHeaderCellDef> From </mat-header-cell>
    <mat-cell *matCellDef="let route"> {{route.from}} </mat-cell>
  </ng-container>

  <!-- To Column -->
  <ng-container matColumnDef="to">
    <mat-header-cell *matHeaderCellDef> To </mat-header-cell>
    <mat-cell *matCellDef="let route"> {{route.to}} </mat-cell>
  </ng-container>

  <!-- Departures Column -->
  <ng-container matColumnDef="departures">
    <mat-header-cell *matHeaderCellDef> Departures </mat-header-cell>
    <mat-cell *matCellDef="let route">{{route.departures}}</mat-cell>
  </ng-container>

  <!-- Duration Column -->
  <ng-container matColumnDef="duration">
    <mat-header-cell *matHeaderCellDef> Duration </mat-header-cell>
    <mat-cell *matCellDef="let route"> {{route.duration}} </mat-cell>
  </ng-container>

  <!-- Price Column -->
  <ng-container  matColumnDef="price">
    <mat-header-cell *matHeaderCellDef> Avg_price </mat-header-cell>
    <mat-cell *matCellDef="let route">
        <button mat-raised-button color="primary">{{route.avg_price}}</button>
    </mat-cell>
  </ng-container>

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

The objective is to be able to loop through the retrieved data outside of mat-table. Apparently, linking dataSource to mat-table initiates an automatic subscription to the service, enabling access to the values within. However, replicating this process outside of mat-table poses a challenge.

Furthermore, I seek guidance on how to access the 'iterable' property present in the RoutesDataSource class from within the Component class. Could someone assist me with this task? Additionally, I'm struggling to implement syntax highlighting in this code!

Your valuable assistance would be highly appreciated. Thank you.

Answer №1

Discovered a solution to the problem by implementing a workaround. I included a new class property named items like this...

public items: Array<any> = []

and then in the ngOnInit() function...

  ngOnInit() {
    this.routesService.getRoutes().subscribe((data) => {
      if (data) {
        this.items = data;
      }
    });
  }

As a result, I was able to access and iterate over the 'items' in my template to achieve the desired result. The only downside is that it requires subscribing to the same service twice in one component, but otherwise, it functions smoothly.

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

NativeScript element isn't showing up

Being relatively new to application development with NativeScript, I find myself in a situation where I need assistance in finding a solution. Drawing from my experience with PHP, I am now looking to create a template for each "page" of the application. Th ...

Showing the child component as undefined in the view

Within my Angular application, I encountered an issue involving a parent component named DepotSelectionComponent and its child component SiteDetailsComponent. The problem arises when an event called moreDetails is emitted to the parent component, triggerin ...

Angular2 URL fragment not recognized in Firefox

My website's main page is divided into different sections: Introduction Services Projects All the content is on the same page. To navigate to a specific section, I use Angular2 fragments in my navigation structure. Here's the HTML snippet for ...

Managing the dispatch of a successful action in a component

In my component, I have a form that adds items to a list. Once an item is successfully added, I want to reset the form using form.resetForm();. However, I am struggling to determine when the action of adding the item has been successful. I attempted to sub ...

Leveraging @ContentChildren in Angular 2 to sort through a component's contents

I am currently working on implementing a search component that can trigger a search(term: string) function on specific child components. If the search on the child fails, the function will return null; otherwise, it will return a reference to the child. M ...

Troubleshooting: The canvas texture in Phaser 3's Update() function is not functioning

I've been attempting to transform this tutorial into Phaser 3: but have encountered an issue with the update() function not working. I also tried using the refresh() function, but that didn't solve the problem either. In my file a.ts, I have cre ...

Using an Angular HttpClient to authenticate with an API by utilizing a token for

I am currently attempting to fetch data from my Jenkins JSON API via HTTPClient. The data I need access to is restricted, so I must authenticate against Jenkins. To do this, I have generated an API Token. However, I am unsure of how to authenticate myself ...

Creating a searchable and filterable singleSelect column in the MUI DataGrid: A step-by-step guide

After three days of working on this, I feel like I'm going in circles. My current task involves fetching data from two API sources (json files) using the useEffect hook and storing them in an array. This array contains a large number of products and a ...

Utilize JSX attributes across various HTML elements

I'm looking for a solution to efficiently add JSX attributes to multiple elements. Here are the example attributes I want to include: class?: string; id?: string; style?: string; And here are the example elements: namespace JSX { interface Int ...

The ion-datetime in Ionic 4 ensures that the floating label always remains visible, even when the input

When an ion-datetime field in Ionic 4 has no value, the label always floats as shown below. Here is my code snippet: <form [formGroup]="statusHandlerForm"> <ion-item class="input-container " align-items-center no-padding> <ion-la ...

Bird's home - The nest is unable to sort out its dependencies

My implementation of a CryptoModule is quite straightforward: import { Module } from '@nestjs/common'; import { CryptoService } from './crypto.service'; @Module({ providers: [CryptoService], exports: [CryptoService], }) export cla ...

Having trouble locating modules or properties with ANTLR4 TypeScript target?

Having reached a frustrating impasse, I am seeking assistance with a perplexing issue. My attempt to integrate TypeScript with ANTLR4 has hit a snag, and despite exhaustive efforts, I am unable to pinpoint the root cause (with limited documentation availab ...

The distinction between <Type>function and function name():Type in TypeScript is essential to understand the various ways

function retrieveCounter(): Counter { let counter = <Counter>function (start: number) { }; counter.interval = 123; return counter; } Upon inspection of line 2 in the code snippet above, I am left wondering why I am unable to use function ...

React with Typescript allows us to refine the callback type depending on the presence of an optional boolean prop

In my project, there's a component <Selector /> that can optionally accept a parameter called isMulti: boolean. It also requires another parameter called onSelected, whose signature needs to change depending on the value of isMulti (whether it i ...

What could be the reason for mocha failing to function properly in a project that is set up

During a unit test in my TypeScript project using mocha, I encountered an issue when setting the project type to module. The error message displayed is as follows: ➜ typescript-project yarn test yarn run v1.22.17 warning package.json: No license field $ ...

Uh-oh! An unexpected type error occurred. It seems that the property 'paginator' cannot be set

I am developing a responsive table using Angular Material. To guide me, I found this helpful example here. Here is the progress I have made so far: HTML <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder ...

Ways to shift placeholder text slightly to the right within a select dropdown?

Struggling with this issue for hours, I can't seem to figure out how to: Adjust the position of the placeholder text (Search) by 10 pixels to the right in my select component Reduce the height of the field (maybe by 5px) without success. Could someo ...

Collection of functions featuring specific data types

I'm currently exploring the idea of composing functions in a way that allows me to specify names, input types, and return types, and then access them from a central function. However, I've encountered an issue where I lose typing information when ...

I encounter an issue while attempting to add Firebase to my Angular project

I am facing an issue while trying to install Firebase in my Angular project. The command I used for installation is: npm install firebase @angular/fire --save However, when running this command, I encountered the following error: npm ERR! Unexpected end ...

Changing setState in React does not update the current state

My challenge lies in altering the value of a TreeSelect component from the antd (antdesign) UI library. I followed their instructions outlined in their documentation, with the only divergence being the use of Typescript. The issue I encounter is with ch ...