Utilizing several data sources within a single mat-table

Hello, I require assistance with a task.

I am trying to display multiple mat-tables with different data sources in my component.ts file

    Groups(){
        this.apiSvc.Cards().subscribe((rsp: any) => { 
            this.groups = rsp;
            this.groups.forEach((row: any) =>{
                this.Employees(row.id);
            });
            
        });
    }
    Employees(id:any){
        this.apiSvc.Groups(id).subscribe((rsp: any) => { 
            this.employees = rsp;
            this.dataSource = new MatTableDataSource(this.employees);
            this.dataSource.paginator = this.paginator;
            console.log(this.dataSource);
        });
    }

As a result, I have multiple data sources like this -

https://i.stack.imgur.com/qkAdU.png

I am looking for a way to use ngFor loop on these data sources to display multiple tables with varying data.

This is the code from my component.html file

  <div fxFlex.gt-lg="75" fxFlex.gt-md="73" fxFlex.gt-xs="100" fxFlex="100">
    <mat-card class="mat-card-employee">
      <mat-card-content>
        <div class="table-responsive">
          <table mat-table [dataSource]="dataSource" class="table employee-list no-wrap">

            <ng-container matColumnDef="#">
              <th mat-header-cell *matHeaderCellDef> ID </th>
              <td mat-cell *matCellDef="let element"> {{element.id}} </td>
            </ng-container>

            <ng-container matColumnDef="username">
              <th mat-header-cell *matHeaderCellDef> User </th>
              <td mat-cell *matCellDef="let element"> {{element.username}} </td>
            </ng-container>
            
            <ng-container matColumnDef="action">
              <th mat-header-cell *matHeaderCellDef> Actions </th>
              <td mat-cell *matCellDef="let element" class="action-link">
                <a (click)="openDialog('Update',element)" class="m-r-10 cursor-pointer"><i class="fa fa-pencil"></i></a>
                <a (click)="openDialog('Delete',element)" class="m-r-10 cursor-pointer">
                  <i class="fa fa-trash text-danger"></i>
                </a>
              </td>
            </ng-container>

            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
            <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
          </table>
          <mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
        </div>
      </mat-card-content>
    </mat-card>
  </div>

If anyone knows how to assign multiple data sources to the [dataSource] property of mat-table, any help would be greatly appreciated. Thank you

Answer №1

If you are facing a challenge in converting multiple calls into one with all the "employees", consider utilizing switchMap and forkJoin to achieve this. Here is an example:

this.apiSvc.Cards().pipe(
   switchMap((rsp:any[])=>{
     // The variable rsp contains an array of "cards"
     // We can create another response using forkJoin
     return forkJoin(
       // Create an array of observables by transforming the previous array
       // using map
       rsp.map(x=>this.apiSvc.Groups(x.id))
     )
   })
).subscribe((res:any[])=>{
   // Here, res holds an array with responses to all your "employees"
   // The response to this.apiSvc.Groups(rsp[0].id) is stored in res[0]
   // The response to this.apiSvc.Groups(rsp[1].id) is stored in res[1]
   ....
   this.dataSource = new MatTableDataSource(res);
   this.dataSource.paginator = this.paginator;
})

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

What is the best way to choose checkboxes from data that is passed dynamically?

https://i.stack.imgur.com/L3k59.png I am looking to add an edit feature to my application. When the user clicks on the edit option, they should be taken to a different page with the previously entered value displayed. While I have successfully retrieved ...

The appearance of the Ionic segment will be altered only when the content input is clicked

Currently working on a photo editing app using ionicv2 and Adobe Creative SDK. Integration of the creative SDK has been successful. Once the CSDK returns the edited file's URL, I navigate to a new page with a segment along with the file URL. The iss ...

Tips for utilizing event handlers such as (onSelect) in place of (change)

Is it possible to use EventEmitter to trigger an event when one or more elements are selected in the UI? I want a solution where the event is triggered once we change the selection. Thank you. <select multiple (change)="setSelected($event.target)"> ...

Execute the CountUp function when the element becomes visible

Currently, I am implementing the following library: https://github.com/inorganik/ngx-countUp Is there a way to activate the counting animation only when the section of numbers is reached? In other words, can the count be triggered (<h1 [countUp]="345 ...

Generating form groups programmaticallyORDynamically

I recently utilized angular-archwizard to implement a wizard step with *ngFor However, I encountered an issue on how to create a dynamic formGroup for each step. In the code below, I managed to create a single formGroup for all steps, but my goal is to ha ...

Developing a Data Generic State Management System in Angular using TypeScript

Implementing a Generic StateManagierService that can handle any type, allowing users to receive new state and data upon state change. However, something seems to be missing. export class StateManagierService<T> { private _state$: BehaviorSubject< ...

Tips for integrating 2 way data binding into model-driven forms

When working with Angular 2, one approach to creating forms is the model-driven method. This means that controls may lose their two-way data binding, unlike in the template-driven approach with ngModel. What is the best way to combine two-way data binding ...

What is the solution to the error message "Unable to assign property of undefined"?

I am currently working on an angular countdown timer and encountering a TypeError when attempting to access a variable from another component. I am struggling to identify the root cause of this issue. Here is the video tutorial that I am using as a referen ...

Angular Protectors: Stop unauthorized access to a URL while allowing authorized refresh

I've developed a Protection feature that blocks users from directly accessing a specific URL, and it's functioning correctly. However, the issue arises when I try to refresh the page as the Protection feature ends up redirecting me. Below is th ...

Integrating mat-table within mat-expansion panel in an Angular 10 application

I am trying to create a list of users with an expandable addresses table when each user is clicked. However, for some reason, the expanded table appears blank. Can anyone help me figure out what the issue might be? You can view the code here: Stackblitz ...

Converting HTML templates into AMD modules using grunt-ts

When using the grunt-ts plugin and specifying the html: ["*.tpl.html"] option, it converts *.tpl.html files into *.tpl.html.js files at the end of the process, creating a global var. Is there a way to configure grunt-ts to output the final .js file in a d ...

The configuration for CKEditor5's placeholder feature seems to be malfunctioning

I am currently experimenting with a customized version of CKEditor 5 known as BalloonBlockEditor. Below is the custom build output that I have created: /** * @license Copyright (c) 2014-2023, CKSource Holding sp. z o.o. All rights reserved. * For licens ...

Updates to Providers in the latest release of Angular 2

When working with angular 2.0.0-rc.1, we implemented a Provider using the new Provider method as shown in the code snippet below: var constAccessor = new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => EJDefaultValueAccessor), ...

A guide on utilizing ngx-translate to convert validation messages in Ionic4

In my ionic4 application, I am configuring it to support two languages - ar and en using ngx-translate library. I have two JSON files, en.json and ar.json, with the following structure: { "LOGIN": { "login": "Login", "emailOrPhone":"EMAIL OR PHO ...

Display a customized modal showcasing the data of a particular user

Seeking advice on how to pass data to a modal based on a specific user. I have an array with user information and would like to display their name and email in a modal when the user is clicked on. Any suggestions on how to accomplish this? ...

Unlock TypeScript code suggestions for extended objects

In my app, I use a configuration file named conf.ts to consolidate config values from other files for better organization. By merging these values, it becomes more convenient to access them using Conf.MY_LONG_NAMED_VALUE rather than Conf.SubCategory.MY_LON ...

Challenges arise when trying to access environment variables using react-native-dotenv in React

I am currently working on two separate projects, one being an app and the other a webapp. The app project is already set up with react-native-dotenv and is functioning as expected. However, when I attempt to use the same code for the webapp, I encounter an ...

Beautiful ExpressionChangedAfterItHasBeenCheckedError

I need your help Input field where I can enter a Student email or IAM, which will be added to a string array List displaying all the students I have added, using a for loop as shown below Delete button to remove a student from the array The list has a sp ...

Warning in VSCODE: Use caution when using experimental decorators

I have been working on an Angular2-Typescript application and created the project using angular-cli with the command: ng new myApp However, I am facing a warning issue when creating a new component with the @Component tag. I have tried to resolve this p ...

Expanding upon React Abstract Component using Typescript

Currently, I am in the process of building a library that contains presentations using React. To ensure consistency and structure, each presentation component needs to have specific attributes set. This led me to create a TypeScript file that can be extend ...