Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a button in ag-grid

I'm trying to learn from this example of ag-grid in order to create a delete button in every row in a grid. The aforementioned example is working, but my code isn't and I can't figure out why.

I'm attaching my code and hope someone can help me.

home.component.ts:

@Component({
  selector: 'home',
  providers: [
    Title
  ],
  styleUrls: [ './home.component.css' ],
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  private items: Item[] = [];
  private gridOptions:GridOptions;
  private columnDefs = [];

  constructor(
    private itemsService: ItemsService
  ) {
    this.gridOptions = {};
    this.columnDefs = this.createColumnDefs();
  }

  remove() {
    alert("yey!")
  }

  ngOnInit(){
    this.itemsService
      .getAll()
      .subscribe(result => {
        this.items = result;
      });
  }

  private createColumnDefs() {
    return [
      {
        headerName: "Foo",
        field: "foo",
        width: 100,
      },
      {
        headerName: "Bar",
        field: "bar",
        width: 100,
      },
      {
        headerName: "",
        field: "_id",
        cellRendererFramework: RemoveButton,
        colId: "params",
        width: 100
      },
    ];
  }
}

home.component.html:

<div>
      <ag-grid-angular #agGrid style="width: 602px; height: 350px;" class="ag-fresh"
                       [gridOptions]="gridOptions"
                       [columnDefs]="columnDefs"
                       [rowData]="items">
      </ag-grid-angular>
  </div>

RemoveButton.ts:

@Component({
  selector: 'remove-button',
  template: `<span><button style="height: 20px" (click)="remove()">X</button></span>`
})
export class RemoveButton implements ICellRendererAngularComp {
  public params: any;

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

  public remove() {
    this.params.context.componentParent.remove();
  }
}

The grid is displayed with all the data, but clicking the button produces this error:

ERROR TypeError: Cannot read property 'componentParent' of undefined
    at RemoveButton.webpackJsonpac__name_.453.RemoveButton.remove

meaning context of params is undefined.

If any further code or information is needed, please let me know.

like image 670
Alon Avatar asked Jun 11 '17 16:06

Alon


1 Answers

I've solved my problem. Obviously context was undefined because I hadn't defined it. Defining the context inside gridOptions has solved that:

this.gridOptions ={
      context: {
        componentParent: this
      }
    };
like image 84
Alon Avatar answered Oct 17 '22 13:10

Alon