I have not found any example or reference about how to shrink an ag-grid table if it already has enough space to fit all columns. The screenshot shows a table spanning the whole window space available, but I would like to center it instead adding auto horizontal margin or vertical align.
I am using Angular 19 and [email protected]
.
This is my base code:
tableponent.ts
<ag-grid-angular
domLayout="autoHeight"
[rowData]="rowData"
[columnDefs]="colDefs"
[gridOptions]="gridOptions"
(gridReady)="onGridReady($event)"
/>
tableponent.ts
import { Component, ElementRef, Input, ViewChild } from "@angular/core";
import { PartService } from "src/app/services/part.service";
import { Part } from "src/app/models/part.model";
import { CommonModule, DatePipe } from "@angular/common";
import { ImgEditComponent } from "src/app/img/edit/editponent";
import { ImgDeleteComponent } from "src/app/img/delete/deleteponent";
import { RouterLink } from "@angular/router";
import { AgGridAngular } from "ag-grid-angular"; // Angular Data Grid Component
import type { ColDef, GridReadyEvent, GridOptions } from "ag-grid-community";
@Component({
standalone: true,
selector: "part-table",
imports: [CommonModule, AgGridAngular],
templateUrl: "./part-tableponent.html",
providers: [DatePipe],
host: { class: 'contents' },
})
export class PartTableComponent {
private partService: PartService;
private datePipe: DatePipe;
parts: Part[] = [];
@Input() editable: boolean = false;
@ViewChild("partTable", { static: false }) table!: ElementRef;
rowData: any[] = []; // Array of row data
colDefs: ColDef[] = [
{ field: "reference", headerName: "Reference", width: 140, maxWidth: 180 },
{ field: "name", headerName: "Name", minWidth: 150 },
{ field: "coating", headerName: "Coating", width: 100, maxWidth: 120 },
{ field: "comment", headerName: "Comment",minWidth: 150 },
{ field: "client_id", headerName: "Client ID", width: 150, maxWidth: 180 },
{ field: "material_id", headerName: "Material ID", minWidth: 100 },
{
field: "created_at",
headerName: "Created At",
valueFormatter: (params) =>
this.datePipe.transform(params.value, "MMM d, y, h:mm a") ?? "",
width: 180,
maxWidth: 200,
},
];
gridOptions: GridOptions = {
columnDefs: this.colDefs,
rowData: this.rowData,
domLayout: "autoHeight",
defaultColDef: {
resizable: true,
sortable: true,
},
};
constructor(partService: PartService, datePipe: DatePipe) {
this.partService = partService;
this.datePipe = datePipe;
}
onGridReady(params: GridReadyEvent): void {
this.partService.getParts().subscribe((data: Part[] | null) => {
if (data) {
this.parts = data;
this.rowData = this.parts.map((part: Part) => ({
reference: part.reference ?? "",
name: part.name ?? "",
coating: part.coating ?? "None",
comment: partment ?? "",
client_id: part.client_id ?? "",
material_id: part.material_id ?? "None",
created_at: part.created_at ?? "",
}));
}
});
}
}