How can I implement a button in Angular Ag Grid to delete a row in a cell render

I have included a button within a cell that I want to function as a row deleter. Upon clicking, it should remove the respective row of data and update the grid accordingly.

Check out the recreation here:https://stackblitz.com/edit/row-delete-angular-btn-cell-renderer-y6gwdubutton?file=src%2Fapp%2Fapp.component.ts

Button rendering component

@Component({
  selector: "btn-cell-renderer",
  template: `
    <button (click)="btnClickedHandler($event)">DELETE!</button>
  `
})
export class BtnCellRenderer implements ICellRendererAngularComp, OnDestroy {
refresh(params: any): boolean {
throw new Error("Method not implemented.");
}
  private params: any;

  agInit(params: any): void {
    this.params = params;
  }

  btnClickedHandler() {
    let selectedData = this.params.api.getSelectedRows();
    this.params.api.updateRowData({remove: selectedData})
  }

App component

@Component({
  selector: "my-app",
  template: `
    <ag-grid-angular
      #agGrid
      style="width: 100%; height: 100vh;"
      id="myGrid"
      class="ag-theme-alpine"
      [columnDefs]="columnDefs"
      [defaultColDef]="defaultColDef"
      [rowData]="rowData"
      [frameworkComponents]="frameworkComponents"
      (gridReady)="onGridReady($event)"
    ></ag-grid-angular>
  `
})
export class AppComponent {
  private gridApi;
  private gridColumnApi;
  frameworkComponents: any;
  private columnDefs;
  private defaultColDef;
  private rowData: [];

  constructor(private http: HttpClient) {
    this.columnDefs = [
      {
        field: "athlete",
        cellRenderer: "btnCellRenderer",
        cellRendererParams: {
          clicked: function(field: any) {
            alert(`${field} was deleted`);
          }
        },
        minWidth: 150
      },
      {
        field: "age",
        maxWidth: 90
      },
      {
        field: "country",
        minWidth: 150
      },
      {
        field: "year",
        maxWidth: 90
      },
      {
        field: "date",
        minWidth: 150
      },
      {
        field: "sport",
        minWidth: 150
      },
      { field: "gold" },
      { field: "silver" },
      { field: "bronze" },
      { field: "total" }
    ];
    this.defaultColDef = {
      flex: 1,
      minWidth: 100
    };
    this.frameworkComponents = {
      btnCellRenderer: BtnCellRenderer
    };
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;

    this.http
      .get(
        "https://raw.githubusercontent.com/ag-grid/ag-grid/master/grid-packages/ag-grid-docs/src/olympicWinnersSmall.json"
      )
      .subscribe(data => {
        this.rowData = data;
      });
  }

The functionality is currently not behaving as intended, any assistance would be greatly appreciated.

Simply recreate it here

Answer №1

  1. The parameter being passed in the columnDefs is unnecessary and can be removed.
  2. No need to call getSelectedRows, just use the params node to access and store the data into an array.

It seems like rowSelection is not enabled on the grid, which is why getSelectedRows is not functioning as expected. You should focus on removing the current row instead of selected rows.

Consider using this code snippet:

let selectedNode = this.params.node;
let selectedData = selectedNode.data;
this.params.api.updateRowData({remove: [selectedData]});

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 an error while trying to run ng serve following ng build

Currently working on my initial Angular application, I am in the process of setting up an existing Angular app on my local machine. Encountered the following error message when running ng serve ERROR in src/app/common-componets/directives/dropFile/d ...

Icon for TypeScript absent from npm package listings

Recently, I created a package and uploaded it to the npm repository. The package was displayed with an icon labeled "ts" on the website. https://i.stack.imgur.com/LoY1x.png The accompanying package.json showcased the inclusion of the "ts" icon - https:// ...

Encountering issues with redirecting the URI when using Oidc-client in an Angular2 application with hash

I am currently following a tutorial on Authenticating Angular2 with Oidc-client and attempting to incorporate the authentication aspect into my project. Since Angular2 is using { provide: LocationStrategy, useClass: HashLocationStrategy } my URLs are no ...

Tips for streamlining the use of http.get() with or without parameters

retrievePosts(userId?: string): Observable<any> { const params = userId ? new HttpParams().set('userId', userId.toString()) : null; return this.http.get(ApiUrl + ApiPath, { params }); } I am attempting to streamline the two http.get ca ...

Utilizing npm/buffer package within a TypeScript module

I'm interested in implementing this NPM package: https://www.npmjs.com/package/buffer I'm unsure about how to convert this line of code into typescript: var Buffer = require('buffer/').Buffer Could you provide me with the correct code ...

What is the best way to access dependencies that are externally defined in the root package.json file?

I'm unsure of the appropriate terminology for this concept. If you have the correct TERM to share or a reference for me to learn more about it, please provide the link. Currently, I am examining our extensive package.json file for various projects. ...

What does the concept of "signaling intent" truly signify in relation to TypeScript's read-only properties?

Currently diving into the chapter on objects in the TypeScript Handbook. The handbook highlights the significance of managing expectations when using the readonly properties. Here's a key excerpt: It’s crucial to clarify what readonly truly signif ...

What is the most effective method for comparing two arrays of objects and extracting the differing values within a React application?

I am currently working on implementing a changelog feature for my website. Let's consider the initial array as initArray: [ { "id": 1, "val1": "2023-08-28", "val2": 1, " ...

What is the best method for setting default values in a multi-select dropdown menu?

Update I managed to resolve the issue by adjusting the model structure so that only the role ids are included in the roles property constructor(private readonly activatedRoute: ActivatedRoute) { const { user, roles } = this.activatedRoute.snapshot.dat ...

I'm curious as to why it's requesting an ID in the newTask function. I followed the tutorial exactly and encountered the same error

An issue has occurred in the project, displaying the following error: Error: src/app/components/add-task/add-task.component.ts:32:25 - error TS2345: Argument of type '{ text: string; day: string; reminder: boolean; }' is not assignable to paramet ...

Error Encountered While Uploading to Firebase Functions: HTTP Error: 400, Mysterious Issue Un

Whilst attempting to deploy the server side of my Angular Universal SSR app to Firebase Functions, I encountered an issue with the error message Upload Error: HTTP Error: 400, Unknown Error. My understanding is that this error commonly occurs when deployi ...

Attempt to create a truncated text that spans two lines, with the truncation occurring at the beginning of the text

How can I truncate text on two lines with truncation at the beginning of the text? I want it to appear like this: ... to long for this div I haven't been able to find a solution. Does anyone have any suggestions? Thanks in advance! ...

Navigating the upgrade of Ag-Grid from version 21 to version 22 within an Angular 8 environment

Recently, Ag-Grid made significant changes to their code in version 22 by deploying it into modules, primarily from the new packages @ag-grid-community/all-modules or @ag-grid-enterprise/all-modules. However, the documentation on their website is quite unc ...

Change the background color of mat-select to match the selected mat-option

<mat-form-field> <mat-select [formControlName]="name"> <mat-option [value]="option.id" [ngStyle]="{backgroundColor: option.color}" *ngFor="let option of list; let i = index" ...

Tips for adjusting the size of a modal window in Ionic 3

Need help customizing the appearance of a modal alert in my app. Here's my current function: customizeModal() { const myModelOpts: ModalOptions = { showBackdrop: false, enableBackdropDismiss: false } const myData = { pa ...

Setting up project with local library installation in Angular 7 - Project configuration

I am currently working on an Angular application that consists of a core module and a shared module. The structure of my project is as follows: ./repo | projects | core | shared | src (my app) When I build libraries, the output folder is dist ...

Utilizing the RxJs map operator to update the attributes of multiple objects within an Angular collection

Inside my angular component, I have the following properties: memberInfoLists$: Observable<MemberInfo[]>; total$: Observable<number>; memberPhotoUrl: string = environment.memberPhotoUrl; memberDefaultPhoto: string = environment.defaultPersonPho ...

Angular Typescript subscription value is null even though the template still receives the data

As a newcomer to Angular and Typescript, I've encountered a peculiar issue. When trying to populate a mat-table with values retrieved from a backend API, the data appears empty in my component but suddenly shows up when rendering the template. Here&a ...

Unexpected Behavior when Passing @Input() Data Between Parent and Child Components in Angular 2 Application

I am currently in the process of abstracting out a tabular-data display to transform it into a child component that can be loaded into different parent components. The main aim behind this transformation is to ensure that the overall application remains "d ...

Bootstrap: Arrange multiple images horizontally within a row

I am trying to design a list item for a game that includes a background, an iconholder with an icon, a title, description, and up to three resources. I have been experimenting with Bootstrap and attempted using a container-fluid with an inner row but the i ...