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

Unable to attach to the property 'displayQR' as it is not recognized by the 'div'?

I'm facing an issue with a div structure that looks like this <div class="empower-btn" [showQR]="showQR" [selectedCoin]="coin" [availableAmount]="getCoinAmount()" [ ...

The following 13 error occurred in the node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js file

Every time I try to use the serialize function in my application on Next, it throws errors. Error - node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js (40:0) @ parseCookieString Error - URI malformed I have attempted numerous soluti ...

Ways to turn off the dragging animation for cdkDrag?

I am facing an issue with cdkDrag where a small preview of the item being dragged shows up. I want to disable this feature and remove any CSS classes related to the dragging state. Can anyone guide me on how to achieve this? As you can see in the image, t ...

The error message is stating that the module located at C://.. does not have an exported member named "firebaseObservable"

Trying to follow an Angular/Firebase tutorial for a class but encountering issues. The FirebaseListObservable is not being imported in my component even though I have followed the tutorial closely. I've looked at similar questions for solutions but ha ...

The Mat-slide-toggle resembles a typical toggle switch, blending the functionalities of

I am facing an issue with a `mat-slide-toggle` on my angular page. Even though I have imported the necessary values in the module, the toggle is displayed as a normal checkbox once the page loads. HTML: <div style="width:100%;overflow:hidden"> < ...

I am experiencing an issue with mydaterangepicker and primeng where it is not displaying properly in the table header. Can anyone assist me with this

I am attempting to integrate mydaterangepicker () with primeng turbotable (since primeng calendar does not meet the requirements), but I am having trouble with its display. Could you please assist me with some CSS code or suggest an alternative solution? ...

tips on rotating an image using nativescript

I'm attempting to insert a picture from my device and then adjust its orientation in nativescript. So far, I've been using imageSource to import the picture, but I'm unsure how to rotate it. If anyone has suggestions for another class that c ...

An unexpected error has occurred in Angular 2 while referencing the service proxy with code asd:18. The error message is: (SystemJS) Unexpected token < SyntaxError: Unexpected token

Forgive me for asking what may seem like a silly question. I am a newcomer to Angular 2 and encountering some problems with the API that my app is utilizing. The consumed Web API is located within the following folder structure: - src - app - Regist ...

Combining cells for certain entries in an Angular data table

Just starting to learn angular, and here's the scenario I'm dealing with: I have a table consisting of 10 columns. Let's say column 4 contains different status categories like children, teen, young, adult, and senior. When displaying all ...

Dynamic Mat-select-trigger that automatically adjusts its size to fit the content

Currently, I am experimenting with an Angular Mat-Select that allows multiple selections. To display the selected values in the value field, I have implemented a custom Mat-Select-Trigger. My goal is to enable automatic resizing of the value field (similar ...

Unable to add chosen elements to array - Angular material mat select allowing multiple selections

Can anyone assist me in figuring out what I am doing wrong when attempting to push data to an empty array? I am trying to only add selected values (i.e. those with checked as true), but I can't seem to get inside the loop This is the current conditi ...

Issue with arrow function not being invoked in a React TypeScript component's prop inside a function

My parent component holds a useState hook to determine if the mobile Nav is open or closed: const [showMobileMenu,setShowMobileMenu] = useState<boolean>(false);. To close the mobile menu, I created an arrow function and passed it down to a child comp ...

Angular 2: Issue with Component not reinitializing when query parameters change

I am currently working with Angular 2 and the latest router component to create a search functionality. Upon clicking the search button for the first time, the router navigates to the search component and retrieves data from the service. However, I have no ...

Exploring the concept of object destructuring in Typescript with imports

Currently, I am in the process of developing the type system for @masala/parser. This allows me to customize the index.d.ts file to fit my needs. When using this as a user, I can: import masala from '@masala/parser' let {C, Stream, F} = masala; ...

What is the proper syntax for using .focus() with the nextElementSibling method in typing?

As I strive to programmatically shift focus in my form using nextElementSibling, I encounter a challenge with typing variables/constants due to working with Typescript... I have managed to achieve success without typing by implementing the following: myF ...

Tips for incorporating multiple services within a single Angular component

Issue found in src/app/header1/header1.component.ts:3:30 - TypeScript error TS2306: The file 'F:/Angular-projects/lawyer-listing/src/app/services/state.service.ts' is not recognized as a module. 3 import { StateService } from '../services/st ...

The program encountered an issue: it cannot access the property 'invalid' because it is undefined

I have a scenario where I am utilizing nested FormGroup in Angular, with the parent formGroup in the HTML and skills as the nested form. However, during validation, the controls are not being found. Can anyone provide assistance with thi ...

Reasons behind Angular HttpClient sorting JSON fields

Recently, I encountered a small issue with HttpClient when trying to retrieve data from my API: constructor(private http: HttpClient) {} ngOnInit(): void { this.http.get("http://localhost:8080/api/test/test?status=None").subscribe((data)=> ...

Material UI offers a feature that allows for the grouping and auto-completion sorting

I am currently utilizing Material UI Autocomplete along with React to create a grouped autocomplete dropdown feature. Here is the dataset: let top100Films = [ { title: "The Shawshank Redemption", genre: "thriller" }, { title: " ...

When additional lines are drawn elsewhere on the HTML5 Canvas, the diagonal lines will gradually appear thicker and more pronounced

For horizontal and vertical lines, using a translation of 0.5 for odd stroke widths results in crisper and sharper lines. But what about diagonal lines? Link to jsfiddle <!DOCTYPE html> <html lang="en"> <body style="background: black"& ...