Angular Ag-Grid: Add PrimeNg P-dropdown as html element in Ag Grid cells

前端 未结 1 1186
青春惊慌失措
青春惊慌失措 2021-01-23 01:23

How to include basic HTML elements in Ag-Grid cells.

Below is my html PrimeNg p-dropdown in MyComponent.html

1条回答
  •  北荒
    北荒 (楼主)
    2021-01-23 01:57

    If you want complex HTML inside AgGrid the cells, then it's time to use cell renderers.

    You need to define a custom component that will implement ICellRendererAngularComp interface and receive the value of a cell through the agInit method.

    prime-ng-dropdown.component.ts

    import { Component, OnInit } from "@angular/core";
    import { ICellRendererAngularComp } from "ag-grid-angular";
    import { ICellRendererParams } from "ag-grid-community";
    @Component({
      selector: "app-prime-ng-dropdown",
      templateUrl: "./prime-ng-dropdown.component.html",
      styleUrls: ["./prime-ng-dropdown.component.css"]
    })
    export class PrimeNgDropdownComponent implements ICellRendererAngularComp {
      params: ICellRendererParams;
    
      cars = [
        { label: "Honda", value: "eHonda" },
        { label: "Jaguar", value: "fJaguar" },
        { label: "Mercedes", value: "gMercedes" }
      ];
    
      agInit(params: ICellRendererParams): void {
        this.params = params;
      }
    
      onChange(value) {
        this.params.data[this.params.colDef.field] = value;
      }
    
      refresh() {
        return true;
      }
    
      doSomething() {}
    }
    

    prime-ng-dropdown.component.html

    
    
    

    Now that we have our component, we need to tell ag-Grid about it. All custom components should be listed in frameworkComponents configuration option. So let’s import our custom cell renderer and specify it in the configuration:

    app.component.ts

    frameworkComponents = {
      primeNgDropdown: PrimeNgDropdownComponent,
      ^^^^^^^^^^^^^^^
    remember this framework key
    };
    

    app.component.html

    Also, you have to pass this component to AgGridModule.withComponents call:

    @NgModule({
      imports:      [ 
          ...
          AgGridModule.withComponents([PrimeNgDropdownComponent])
        ],
    

    Finally, you only need to specify which component to use for your column through specifying framework key in cellRenderer option:

    columnDefs = [
      ...
      {
        headerName: "DropdownColumn",
        field: "ddValue",
        cellRenderer: 'primeNgDropdown' <----------------- this one
      }
    ];
    

    Stackblitz Example

    0 讨论(0)
提交回复
热议问题