Search code examples
angularag-gridag-grid-angular

create multiple ag grid table dynamically


Need to create multiple ag grid table dynamically. But I am facing below issue

     Error occurs in the template of component AppComponent.
src/app/app.component.html:3:18 - error NG5002: Parser Error: Unexpected token '}' at column 22 in [{{response.columndef}}] in D:/angular/ag-custom/src/app/app.component.html@2:17

3     [columnDefs]={{response.columndef}}>

app.component.html

 <div *ngFor="let response of data.response">
  <ag-grid-angular style="width: 100%; height: 500px;" class="ag-theme-alpine" [rowData]= {{ response.rowData }}
    [columnDefs]= {{ response.columndef }}>
  </ag-grid-angular>
</div>

app.component.ts

import { Component } from '@angular/core';
import { GridRes } from './gridres.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ag-custom';


data: GridRes={"response":[{"label":"Table1","columndef":[{"header":"Make","field":"make","sortable":true,"filter":true,"resizable":true},{"header":"Model","field":"model","sortable":true,"filter":true,"resizable":true},{"header":"Price","field":"price","sortable":true,"filter":true,"resizable":true}],"rowData":[{"make":"Toyota","model":"Celica","price":35000},{"make":"Ford","model":"Mondeo","price":32000},{"make":"Porsche","model":"Boxter","price":72000}]},{"label":"Table2","columndef":[{"header":"Make","field":"make","sortable":true,"filter":true,"resizable":true},{"header":"Model","field":"model","sortable":true,"filter":true,"resizable":true},{"header":"Price","field":"price","sortable":true,"filter":true,"resizable":true}],"rowData":[{"make":"Toyota","model":"Celica","price":35000},{"make":"Ford","model":"Mondeo","price":32000},{"make":"Porsche","model":"Boxter","price":72000}]}]};

}

GridRes Model

export class GridRes {
    response: Response[];
}
export class Response {
    label: string;
    columndef: Columndef[];
    rowData: RowData[];
}
export class Columndef {
    header: string;
    field: string;
    sortable: boolean;
    filter: boolean;
    resizable: boolean;
}

export class RowData {
    make: string;
    model: string;
    price: number;
}

How I can create multiple tables based on the json data


Solution

  • bindings should be written like [columnDefs]="response.columndef" instead of what you did (string interpolation) - [columnDefs]= {{ response.columndef }} (change this for all inputs, not just columDefs)

    so your template should look like:

    <div *ngFor="let response of data.response">
      <ag-grid-angular style="width: 100%; height: 500px;" class="ag-theme-alpine" [rowData]="response.rowData"
        [columnDefs]='response.columndef">
      </ag-grid-angular>
    </div>