Search code examples
javascriptangularag-gridag-grid-angular

Angular ag-Grid: how to autogenerate default template for cell but with different name of field?


I have ag-grid when a lot of columns have specific templates. But some of data that I put into table are nothing more than just text until now.. I want to put something more for default case:

<ng-template #defaultRecord let-record>
  ADDITIONAL THINGS HERE
  <!-- CHOOSEN FIELD HERE -->
</ng-template>

So I have method for autogenerating columns:

  private generateColumn(headerNameKey: string, colId: string, ngTemplate: TemplateRef<any>, filter = true, sortable = true, field?: string) {
  const headerName = headerNameKey ? this.translateService.instant(headerNameKey) : '';
  return {
  headerName,
  field,
  sortable,
  filter,
  colId,
  cellRendererFramework: CellRendererComponent,
  cellRendererParams: {
    ngTemplate
  }
};
}

And I don't know how to use unspecified field in template. For example I get from api data when field is called "XYZ", how to make display it in my default template?

In this case:

<ng-template #defaultRecord let-record>
  ADDITIONAL THINGS HERE
  <span> Value of XYZ param</span>
</ng-template>

Can someone help me? Thanks!

EDIT 1:

Custom CellRenderer Component:

export class CellRendererComponent implements ICellRendererAngularComp {
  template: TemplateRef<any>;
  templateContext: { $implicit: any, params: ICellRendererParams };

  agInit(params: ICellRendererParams) {
    this.template = params['ngTemplate'];
    this.refresh(params);
  }

  refresh(params: ICellRendererParams): boolean {
    this.templateContext = {
      $implicit: params.data,
      params
   };
    return true;
  }
}

And how params in agInit method looks: enter image description here

And as You can see in the picture, in the template I want to display value of Fields.Date param that is defined field. How I suppose to use it in the template above?


Solution

  • if I understand correctly what you want to do. Then here is one way.

    You add context parameter to the template context.

    <ng-template #defaultRecord let-record let-value="value">
        ADDITIONAL THINGS HERE
        <span> {{value}} </span>
    </ng-template>
    

    And you calculate this value in renderer component.

    refresh(params: ICellRendererParams): boolean {
        const valuePath = params.colDef.field;
        const value = _.get(params.data, valuePath); // using lodash
        this.templateContext = {
            $implicit: params.data,
            params,
            value
        };
        return true;
    }
    

    I am using lodash function, but you can use other library or write simple method to get value from the object using its path.