What is the best method to retrieve the value of a cell in a different cell within the same row in an Angular Material Data-Table?

I am working with an Angular Material Data Table that has four columns. In every row, the last cell contains a button with an on-click function attached to it. I need to pass the value from the first cell ("Name") as a parameter in the corresponding button's function when clicked. Is there a way to achieve this?

Currently, the restart() function does not have any parameters, but I would like to add one so that I can pass it to my API.

Here is the code for table.component.ts:


    import { Component, OnInit } from '@angular/core';
    import { PowershellService } from 'src/app/services/powershell.service';
    import { Observable } from 'rxjs';
    import { DataSource } from '@angular/cdk/collections';
    import { powershell } from 'src/app/models/powershell.model';
    import { MatSnackBar } from '@angular/material/snack-bar';

    @Component({
      selector: 'app-apps-table',
      templateUrl: './apps-table.component.html',
      styleUrls: ['./apps-table.component.scss']
    })
    export class AppsTableComponent implements OnInit {

      dataSource = new PowerShellDataSource(this.powershellService);
      displayedColumns = ['Name', 'Description', 'Status', 'options'];

      constructor(private powershellService: PowershellService,
        private snackBar: MatSnackBar) { }

      ngOnInit() {
      }
      
      restart() {
        this.powershellService.getRestart()
          .subscribe((data) => {
            this.snackBar.open(data, 'Close', {
              duration: 4000,
              panelClass: ['snackbar']
            });
          },
            (error) => {
              console.log(error);
              this.snackBar.open(error, 'Close', {
                duration: 4000,
                panelClass: ['snackbar']
              });
            });    
      }
    }


    export class PowerShellDataSource extends DataSource<any> {

      constructor(private powershellService: PowershellService) {
        super();
      }

      connect(): Observable<powershell[]> {
        return this.powershellService.getPowershellApps();
      }

      disconnect() { };
}

The HTML code for table.component.html:


    <div>
        <mat-table [dataSource]="dataSource" class="mat-elevation-z3">

            <ng-container matColumnDef="Name">
                <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
                <mat-cell *matCellDef="let powershell">{{powershell.Name}}</mat-cell>
            </ng-container>

            <ng-container matColumnDef="Description">
                <mat-header-cell *matHeaderCellDef>Description</mat-header-cell>
                <mat-cell *matCellDef="let powershell">{{powershell.Description}}</mat-cell>
            </ng-container>

            <ng-container matColumnDef="Status">
                <mat-header-cell *matHeaderCellDef>Status</mat-header-cell>
                <ng-container *matCellDef="let powershell">
                    <mat-cell [ngSwitch]="powershell.Status">
                        <ng-container *ngSwitchCase="'Running'">
                            <mat-chip-list>
                                <mat-chip class="running" selected>Running</mat-chip>
                            </mat-chip-list>
                        </ng-container>
                        <ng-container *ngSwitchCase="'Stopped'">
                            <mat-chip-list>
                                <mat-chip class="stopped" selected>Stopped</mat-chip>
                            </mat-chip-list>
                        </ng-container>
                        <ng-container *ngSwitchDefault>
                            <mat-chip-list>
                                <mat-chip>{{powershell.Status}}</mat-chip>
                            </mat-chip-list>
                        </ng-container>
                    </mat-cell>
                </ng-container>
            </ng-container>

            <ng-container matColumnDef="options">
                <mat-header-cell *matHeaderCellDef>Options</mat-header-cell>
                <mat-cell *matCellDef="let powershell">
                    <button mat-icon-button [matMenuTriggerFor]="appMenu">
                        <mat-icon>desktop_mac</mat-icon>
                    </button>
                </mat-cell>
            </ng-container>

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

        </mat-table>
    </div>

<mat-menu #appMenu="matMenu">
    <button mat-menu-item (click)="restart()">Restart</button>
</mat-menu>

Answer №1

One way to pass data to a menu is by following these steps:

Start by making this adjustment:

<button mat-icon-button [matMenuTriggerFor]="appMenu">

Change it to this: (using matMenuTriggerData to provide context data)

<button mat-icon-button [matMenuTriggerFor]="appMenu" [matMenuTriggerData]="{ps: powershell}>

Next, update your mat-menu like this:

<mat-menu #appMenu="matMenu">
  <ng-template matMenuContent let-ps="ps">
    <button mat-menu-item (click)="restart(ps)">Restart</button>
  </ng-template>
</mat-menu>

Take note of the matMenuContent, which allows you to utilize the let- template input variable.

In your TypeScript file, you can access all fields of the selected row (powershell):

  restart(powershell) {
    alert('restart: ' + JSON.stringify(powershell));
  }

console.log(powershell.Name);

For more information, refer to the Angular Material documentation here

and view a functioning example on Stackblitz

Answer №2

<mat-menu #appMenu="matMenu">
    <button mat-menu-item (click)="refresh(powershell.Name)">Refresh</button>
</mat-menu>

Experiment with it in this manner

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

Angular 13.0 version is experiencing issues when trying to run the "ng serve" command

After installing the npm module, I encountered a problem while using node.js version 14.17.6. I am a beginner in Angular and struggling to find a solution due to not using the latest Angular CLI version. Any help would be greatly appreciated. Thank you in ...

The typescript error "Cannot read properties of undefined" is encountered while trying to access the 'map' function

I was attempting to follow a guide on creating an app using typescript and react, but I'm encountering an error that says "Cannot read properties of undefined (reading 'map')". I'm not sure why this is happening, can someone please offe ...

Is there a way to utilize an Angular Material checkbox without any extra gaps or spacing?

Currently, I am working with Angular Material and trying to figure out how to remove the default spacing around the checkbox. The checkboxes in Angular Material are typically surrounded by some space (as shown in the image). Is there a simple way to elimin ...

Error in Angular Material: SassError - The CSS after "@include mat" is invalid. Expected 1 selector or at-rule, but found ".core();"

My Angular 11 project was running smoothly with Angular Material version 11 until I decided to update everything to Angular 12, including Material. However, after the update, the styles.scss file that comes with Material started throwing errors. The comple ...

The licensed Angular Google Map component is failing to display the map

I've been experimenting with the new Google Map component developed by the Angular Team (from the package @angular/google-maps) with the help of this insightful tutorial. Unfortunately, I'm facing an issue where the map isn't being displaye ...

Guide on integrating google play services into a nativescript plugin seed?

I am developing a plugin for NativeScript using the recommended nativescript-plugin-seed available at this link. In my plugin, I require access to the Google Location service, but I am facing issues with accessing it. In order to implement the required de ...

Are child routes permitted to be utilized without the need for router outlets, specifically for tab contents within a main component?

Can different components be rendered for each tab in a tab menu without using router outlets? Within my parent component, there is a template containing a tab menu component with each tab item having an ng template associated with it. I have set the tabs p ...

Retrieving user input from one component to be used in another component in Angular

I'm currently working on a structure that involves a navbar component and a form component https://i.stack.imgur.com/nPRLO.png Initially, I have a navbar component where I load user data using an ID stored in the session. In the right side component ...

"Loop through an array using forEach leads to a subscription that

I am a beginner in Angular and struggling to understand how async functions work. I have written the following code, but I am encountering an error: GET https://localhost:44353/api/ecams/id/undefined 400 and ["The value 'undefined' is not va ...

Validation with zod is unsuccessful under certain conditions

I am facing an issue with my form that contains a radio button with three input fields inside it. The submit button is supposed to validate that only one of the input fields is correctly entered. Despite using refine() in zod validation, I cannot get it ...

Angular 4: Implementing toggle switch functionality in Angular 4 by binding boolean values retrieved from the database

Within my application, I am facing an issue with binding a toggle switch to data stored in the database. The data in the database is represented by a field called Status, which can have values of True or False. My goal is to incorporate toggle switch butto ...

The attribute 'y' is not found within the data type 'number'

Currently working on a project using Vue.js, Quasar, and TypeScript. However, encountering errors that state the following: Property 'y' does not exist on type 'number | { x: number[]; y: number[]; }'. Property 'y' does not ...

Tips on expanding properties for Material-UI components with Typescript?

My goal is to enhance the props of the Button component from Material-UI using typescript in order to pass additional props to its children. import { NavLink } from 'react-router-dom'; import { Button } from 'material-ui'; <Button ...

Syntax for Angular services

I need help figuring out how to send specific data to the backend of my node.js and mysql application in order to trigger an email notification. Specifically, I want to pass two objects (account and labSwap) using a post method. What is the correct syntax ...

Exploring the intricacies of pattern matching with JavaScript visualization

I am currently working on improving my pattern matching function by creating a visualizer for it. To achieve this, I need to slow down the execution of each comparison. My approach involves declaring the i and j variables outside of the function so that I ...

Ordering an array in Angular 2: A step-by-step guide

I am working on an Ionic 2 app with an older version of AngularJS that does not have the orderby pipe by default. As a result, I have an array structured like this: <div *ngFor="let boatBooking of boatBookings" style="padding: 0px; margin:0px;"> ...

Strategies for effectively conveying jQuery and Angular

I have integrated jQuery DataTable into my code. I am facing an issue with the dataTables_scrollBody class which requires me to add a custom scroll bar. This is necessary because on Linux, the touch screen functionality in Chrome is not working effectively ...

Can callback argument types be contingent on certain conditions? For example, could argument 0 be null if argument 1 is a string?

I am attempting to implement conditional type logic for the parameter types of a callback function. In this scenario, the first argument represents the value while the second argument could be an error message. type CallbackWithoutError = (value: string, ...

Error: No 'map' property found in 'TwitterserviceService' type

Currently, I am in the process of learning how to develop simple and basic Angular applications. As part of my learning journey, I decided to incorporate my Twitter timeline into one of my projects. To aid me in this endeavor, I referred to various online ...

Can you explain the concept of injection context within Angular version 16 and later?

I have come across the term "Injection context" and am trying to understand what it entails. In Angular, there are several things that are connected to injection context: EnvironmentInjector#runInContext injectionContext runInInjectionContext inject() Fr ...