Hide column headers in ag-grid - ag-grid

Here is a very basic sample with ag-grid: https://stackblitz.com/edit/ag-grid-react-hello-world-qqjk5k
import React from 'react';
import { render } from 'react-dom';
import { AgGridColumn, AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';
const App = () => {
const rowData = [
{ make: 'Toyota', model: 'Celica', price: 35000 },
{ make: 'Ford', model: 'Mondeo', price: 32000 },
{ make: 'Porsche', model: 'Boxter', price: 72000 },
];
return (
<div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
<AgGridReact rowData={rowData}>
<AgGridColumn field="make" headerHeight="0"></AgGridColumn>
<AgGridColumn field="model" headerHeight="0"></AgGridColumn>
<AgGridColumn field="price" headerHeight="0"></AgGridColumn>
</AgGridReact>
</div>
);
};
render(<App />, document.getElementById('root'));
I would like to not show the column headers, thus I put headerHeight="0". But it did not work.
So does anyone know how to hide the column headers?
Additionally, I would like to pass a two-dimensional array [['Toyota', 'Celica', 35000],['Ford', 'Mondeo', 32000], ['Porsche', 'Boxter', 72000]] (rather than object) to the data. Does anyone know how to make ag-grid accept that? Do we have to convert the data by ourselves?

does anyone know how to hide the column headers?
why don't you use CSS for this?
.ag-root .ag-header {
display: none;
}
Do we have to convert the data by ourselves?
Yes, without that, ag-grid won't be able to understand the format you're receiving from server.

Related

How to cancel all chnages in row

I have a ag grid table with edit enabled on each cell. I want to reset all changes the user has made on specfic button on click.
To achieve this we need to keep our original data separate from what the user will edit - this is done by making a deep copy:
const originalData = [{ make: 'Toyota', model: 'Celica', price: 35000},
{ make: 'Ford', model: 'Mondeo', price: 32000 },
{ make: 'Porsche', model: 'Boxster', price: 72000 },
];
let copyData = originalData.map((d) => ({ ...d }));
After the cells have been edited - in our function we remake our deep copy then call SetRowData on the deep copy:
const resetChanges = () => {
copyData = originalData.map((d) => ({ ...d }));
gridDataRef.current.gridApi.setRowData(copyData);
};
Heres a live example: https://plnkr.co/edit/1GpqhekV2A5XePSn?open=index.jsx

Click event for group header on ag-grid angular

I am using ag-angular-grid in this I have group header and child columns also.
I want to know click event of that group header click.
below how I create header :
{
headerName: "<span id='performanceData'>Performance</span> <i class='fa fa-eye group-open-settings-button' aria-hidden='true' data-group='PerformanceData' ></i>",
groupId: "PerformanceData",
marryChildren: false,
onCellValueChanged:event=>{
console.log('trst');
},
children: [
{
headerName: "Talent Decision",
headerTooltip: "Talent Decision",
on click this i wants to open a popup.
any idea?
You will need to create a separate component for your custom group header. This can be done by implementing the IHeaderGroupAngularComp and using headerGroupComponentFramework, as stated on the documentation for the Header Group component.
Here is a rough sketch on how you can get it done.
First and foremost, on your main component that is using ag-grid, we will need to bind the input properties for frameworkComponents, and import your custom header group component.
On the component.html,
<ag-grid-angular style="width: 100%; height: 350px;" class="ag-theme-balham"
[columnDefs]="columnDefs"
[frameworkComponents]="frameworkComponents"
<!-- other properties -->
</ag-grid-angular>
On the component.ts, define the component which will be binded to your frameworkComponents, and for your custom header.
import { CustomHeaderGroupComponent } from '../custom-header-group-component/custom-header-group.component';
constructor() {
this.frameworkComponents = {
customHeaderGroupComponent: CustomHeaderGroupComponent,
};
this.columnDefs = [
{
headerGroupComponent: 'customHeaderGroupComponent',
// other properties for your group header
}
];
}
Do not forget to include your custom header group component on your module.ts too:
import { CustomHeaderGroupComponent } from "./custom-header-group-component/custom-header-group.component";
#NgModule({
imports: [
AgGridModule.withComponents(
[
CustomHeaderGroupComponent
]
),
// other imports
],
declarations: [
CustomHeaderGroupComponent,
// other components
],
// others
})
On your custom component.html template for the header group, you can then bind the (click) event to the header to it:
<div (click)="openPopup($event)"><span id='performanceData'>Performance</span> <i class='fa fa-eye group-open-settings-button' aria-hidden='true' data-group='PerformanceData' ></i></div>
And on your component.ts for the header group, you can define the openPopup() method:
import { Component } from '#angular/core';
import { IHeaderGroupAngularComp } from 'ag-grid-angular';
import { IHeaderGroupParams } from 'ag-grid-community';
.
.
.
export class CustomHeaderGroupComponent implements IHeaderGroupAngularComp {
params: IHeaderGroupParams;
agInit(params: IHeaderGroupParams) {
this.params = params;
}
.
.
openPopup() {
// handle the rest to enable to opening of the popup
}
}
The full working demo is actually available here, though it is a complete demo for all the features.

How to format data before displaying it on ag-grid

I've just discovered ag-grid. I'm using it on angular2+ and loading data from api. One of fields is date, but its in ISO format. I've been trying to format it, is there any way to do it, is it possible to add pipe or some other way? Usually i do it like this {{ someISODate | date: 'dd.MM.yyyy HH:mm'}}. Do i really have to format it manually in component before displaying it? Also I was wondering if its possible to add two fields under one column. Why? Well i have column author, and in data that im getting from api i have author.firstname and author.lastname, and now I wanna display both fields in same column. Any hints or examples are more than welcomed.
columnDefs = [
{headerName: 'Datum kreiranja', field: 'createdAt' }, //<-- wanna format it
{headerName: 'Vrsta predmeta', field: 'type.name' },
{headerName: 'Opis', field: 'description'},
{headerName: 'Kontakt', field: 'client.name'},
{headerName: 'Autor', field: 'author.firstname'}, //<-- wanna display author.lastname in same cell
{headerName: 'Status', field: 'status.name'}
];
You can do this by using cellRenderer (or valueFormatter as pointed in the UPDATE) and moment library.
{
headerName: 'Datuk kreiranja', field: 'createdAt',
cellRenderer: (data) => {
return moment(data.createdAt).format('MM/DD/YYYY HH:mm')
}
}
If you don't want to use moment, then below is how you can do it.
cellRenderer: (data) => {
return data.value ? (new Date(data.value)).toLocaleDateString() : '';
}
For Author field as well,
cellRenderer: (data) => {
return data.author.firstname + ' ' + data.author.lastname;
}
Reference: ag-grid: Cell Rendering
UPDATE
As suggested by #Mariusz, using valueFormatter makes more sense in this scenario. As per documentation, Value Formatter vs Cell Renderer
value formatter's are for text formatting and cell renderer's are for
when you want to include HTML markup and potentially functionality to
the cell. So for example, if you want to put punctuation into a value,
use a value formatter, but if you want to put buttons or HTML links
use a cell renderer.
You can use valueFormatter
{headerName: 'Datuk kreiranja', field: 'createdAt', valueFormatter: this.dateFormatter},
Create a small function:
dateFormatter(params) {
return moment(params.value).format('MM/DD/YYYY HH:mm');
}
First of all thanks to Paritosh.
The issue I was facing is the date field I was receiving from API is on the below format
"endDateUTC":"2020-04-29T12:00:00",
I have followed Paritosh solution using cellrenderer along with moment library but the value was always formatted to today's date for some reason.
The below solution is using valueFormatter with moment library.
This is for Angular2+ version. The job is really simple
In your .ts file:
import * as moment from 'moment';
{
headerName: 'End Date',
field: 'endDateUTC',
minWidth: 80,
maxWidth: 100,
valueFormatter: function (params) {
return moment(params.value).format('D MMM YYYY');
},
},
And the output you will get is:
End date:
29 APR 2020
Please feel free to change the date format you need.
Hope this will be helpful to some one.
I just want to expand on Vishwajeet's excellent answer from April 2019. Here's how I would use his code, and which import commands would be required:
import { Component, OnInit, ViewChild, LOCALE_ID, Inject } from '#angular/core';
constructor(#Inject(LOCALE_ID) private locale: string)
{
}
columnDefs = [
{ headerName: 'Last name', field: 'lastName' },
{ headerName: 'First name', field: 'firstName' },
{ headerName: 'DOB', field: 'dob', cellRenderer: (data) => { return formatDate(data.value, 'd MMM yyyy HH:mm', this.locale); }},
{ headerName: 'Policy start', field: 'policyStartDate', cellRenderer: (data) => { return formatDate(data.value, 'd MMM yyyy HH:mm', this.locale); } },
{ headerName: 'Policy end', field: 'policyEndDate', cellRenderer: (data) => { return formatDate(data.value, 'd MMM yyyy HH:mm', this.locale); } }
]
And your agGrid would contain something like this:
<ag-grid-angular
class="ag-theme-material"
[rowData]="rowData"
[columnDefs]="columnDefs"
</ag-grid-angular>
This works really nicely, but I decided to move the date formatting into it's own cell renderer for a few reasons:
The code above will display null values as "1 Jan 1970 01:00"
You would need to repeat this code, plus the imports and #Inject, into any control which uses it.
It repeats the logic each time, so if you wanted to change the date format throughout your application, it's harder to do. Also, if a future version of Angular broke that date formatting, you'd need to apply a fix for each occurrence.
So, let's move it into it's own cell renderer.
My DateTimeRenderer.ts file looks like this:
import { Component, LOCALE_ID, Inject } from '#angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';
import { ICellRendererParams } from 'ag-grid-community';
import { formatDate } from '#angular/common';
#Component({
selector: 'datetime-cell',
template: `<span>{{ formatTheDate(params.value) }}</span>`
})
export class DateTimeRenderer implements ICellRendererAngularComp {
public params: ICellRendererParams;
constructor(#Inject(LOCALE_ID) public locale: string) { }
agInit(params: ICellRendererParams): void {
this.params = params;
}
formatTheDate(dateValue) {
// Convert a date like "2020-01-16T13:50:06.26" into a readable format
if (dateValue == null)
return "";
return formatDate(dateValue, 'd MMM yyyy HH:mm', this.locale);
}
public onChange(event) {
this.params.data[this.params.colDef.field] = event.currentTarget.checked;
}
refresh(params: ICellRendererParams): boolean {
return true;
}
}
In my app.module.ts file, I need to import this Component:
import { DateTimeRenderer } from './cellRenderers/DateTimeRenderer';
#NgModule({
declarations: [
AppComponent,
DateTimeRenderer
],
imports: [
BrowserModule,
AgGridModule.withComponents([DateTimeRenderer])
],
providers: [],
bootstrap: [AppComponent]
})
And now, back in my Component which uses the agGrid, I can remove LOCALE_ID, Inject from this line:
import { Component, OnInit, ViewChild, LOCALE_ID, Inject } from '#angular/core';
..remove it from our constructor...
constructor()
{
}
..import our new renderer...
import { DateTimeRenderer } from './cellRenderers/DateTimeRenderer';
..and change the columnDefs to use the new renderer:
columnDefs = [
{ headerName: 'Last name', field: 'lastName' },
{ headerName: 'First name', field: 'firstName' },
{ headerName: 'DOB', field: 'dob', cellRenderer: 'dateTimeRenderer' },
{ headerName: 'Policy start', field: 'policyStartDate', cellRenderer: 'dateTimeRenderer' },
{ headerName: 'Policy end', field: 'policyEndDate', cellRenderer: 'dateTimeRenderer' }
]
frameworkComponents = {
dateTimeRenderer: DateTimeRenderer
}
And I just need to make sure my agGrid knows about this new frameworkComponents section:
<ag-grid-angular
class="ag-theme-material"
[rowData]="rowData"
[columnDefs]="columnDefs"
[frameworkComponents]="frameworkComponents" >
</ag-grid-angular>
And that's it.
Again, the nice thing about this is I can use this date formatter anywhere throughout my code, and all the logic is in one place.
It's just shocking that, in 2020, we actually need to write our own date formatting function for an up-to-date grid like agGrid... this really should've been included in the agGrid libraries.
For Angular, if you want to do this without moment.js you can try something like below:
import { Component, OnInit, Inject, LOCALE_ID } from '#angular/core';
import { formatDate } from '#angular/common';
#Component({
selector: 'app-xyz'
})
export class xyzComponent implements OnInit {
constructor( #Inject(LOCALE_ID) private locale: string ) {
}
columnDefs = [
{headerName: 'Submitted Date', field: 'lastSubmittedDate', cellRenderer: (data) => {
return formatDate(data.value, 'dd MMM yyyy', this.locale);
}];
}
This component is using format date of angular/common
(Working & Optimized solution for date formatting is here!)
Tested on Angular 8 with dynamic data where date is coming like 2019-11-16T04:00:00.000Z.
In Ag-grid if you use valueFormatter, then no need of including "field:'Order Date'".
Also following Ragavan Rajan's answer. So you need to install moment.js in your angular CLI.
Working code and installation is below:
//Install moment.js in angular 8 cli.(no need of --save in latest versions
npm install moment
//In your component.ts
import * as moment from 'moment';
//Inside your colDef of ag-grid
{
headerName: "Effective Date",
field: "effectiveDate",
valueFormatter: function (params){
return moment (params.value).format ('DD MMM, YYYY');
}
/*
* This will display formatted date in ag-grid like 16 Nov, 2019.
* field name's value is from server side.(column name).
*/
If you are using AdapTable then you can do it via their Format Column function which can be applied either at design-time or run-time. And there you can choose pretty much any DateTime format that you want.
https://demo.adaptabletools.com/style/aggridformatcolumndemo
if you have two subfields like "Start Date" and "End Date" then you are supposed to do like this:
{
headerName: "Date Range",
children: [
{
field: 'StartDate',
cellRenderer: (data) => {
return data ? (new Date(data.value)).toLocaleDateString() : '';
}
},
{
field: 'EndDate',
cellRenderer: (data) => {
return data ? (new Date(data.value)).toLocaleDateString() : '';
}
}
],
}
I'm Using Angular 10, And I achieved the date formatting by using cellRenderer and DatePipe
{
field: "fieldName",
cellRenderer: (res) => {
const datepipe : DatePipe = new DatePipe("en-US");
var x = datepipe.transform(res.data.fieldName.split('T')[0],"yyyy-MM-dd");
return x;
}
},
Split('T') is used because when you call the Api, date comes in this format
"2021-07-31T00:00:00.000Z".
Try this:
{
headerName: 'Order Date',
field: 'OrderDate',
valueFormatter: function (params) {
var nowDate = new Date(parseInt(params.value.substr(6)));
return nowDate.format("yyyy-mm-dd");
}

Angular 4 Data table implementation into my APP

I have created custom component DisplayTableComponent in my project. I want to incorporate Angular 4 Data table on my data for display purpose.
DisplayTableComponent.TS is as follows
import { Component, OnInit } from '#angular/core';
import { DataTableResource } from 'angular-4-data-table';
import { DataTableModule } from 'angular-4-data-table';
import persons from './data-table-demo1-data';
#Component({
selector: 'app-display-table',
templateUrl: './display-table.component.html',
styleUrls: ['./display-table.component.css']
})
export class DisplayTableComponent implements OnInit {
itemResource = new DataTableResource(persons);
items = [];
itemCount = 0;
constructor() {
this.itemResource.count().then(count => this.itemCount = count);
}
ngOnInit() {
}
reloadItems(params) {
// this.itemResource.query(params).then(items => this.items = items);
}
// special properties:
rowClick(rowEvent) {
console.log('Clicked: ' + rowEvent.row.item.name);
}
rowDoubleClick(rowEvent) {
alert('Double clicked: ' + rowEvent.row.item.name);
}
rowTooltip(item) { return item.jobTitle; }
}
My Html Template is as follows
<p>
display-table works!
</p>
<div style="margin: auto; max-width: 1000px; margin-bottom: 50px;">
<data-table id="persons-grid"
headerTitle="Employees"
[items]="items"
[itemCount]="itemCount"
(reload)="reloadItems($event)"
(rowClick)="rowClick($event)"
(rowDoubleClick)="rowDoubleClick($event)"
[rowTooltip]="rowTooltip"
>
<data-table-column
[property]="'name'"
[header]="'Name'"
[sortable]="true"
[resizable]="true">
</data-table-column>
<data-table-column
[property]="'date'"
[header]="'Date'"
[sortable]="true">
<ng-template #dataTableCell let-item="item">
<span>{{item.date | date:'yyyy-MM-dd'}}</span>
</ng-template>
</data-table-column>
<data-table-column
property="phoneNumber"
header="Phone number"
width="150px">
</data-table-column>
<data-table-column
[property]="'jobTitle'"
[header]="'Job title'"
[visible]="false">
</data-table-column>
<data-table-column
[property]="'active'"
[header]="'Active'"
[width]="100"
[resizable]="true">
<ng-template #dataTableHeader let-item="item">
<span style="color: rgb(232, 0, 0)">Active</span>
</ng-template>
<ng-template #dataTableCell let-item="item">
<span style="color: grey">
<span class="glyphicon glyphicon-ok" *ngIf="item.active"></span>
<span class="glyphicon glyphicon-remove" *ngIf="!item.active"></span>
</span>
</ng-template>
</data-table-column>
</data-table>
</div>
Now, The temporary source data file (data-table-demo1-data.ts) is as
export default [
{ 'name': 'Aaron 2Moore', 'email': 'aaa#aa.com', 'jobTitle': 'Regional Configuration Producer',
'active': true, 'phoneNumber': '611-898-6201', 'date': '2015-11-06T07:21:25.510Z' },
{ 'name': 'Yvonne Conroy Mrs.', 'email': 'sss#ssss.com', 'jobTitle': 'Global Mobility Orchestrator',
'active': false, 'phoneNumber': '115-850-0969', 'date': '2014-12-20T00:48:40.276Z' },
]
My app.Module.TS is as follows
import { BrowserModule } from '#angular/platform-browser';
import { NgModule,CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { Routes, RouterModule} from '#angular/router';
import { DataTableModule } from 'angular-4-data-table';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { MovieComponent } from './movie/movie.component';
import { DisplayTableComponent } from './display-table/display-table.component';
const appRoute: Routes =[
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{path:'home', component:HomeComponent},
{path:'Movie', component:MovieComponent},
{path:'table', component:DisplayTableComponent},
];
#NgModule({
declarations: [
AppComponent,
HomeComponent,
MovieComponent,
DisplayTableComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoute)
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Could you please help me. I am getting below error
ERROR in ./node_modules/angular-4-data-table/src/index.ts
Module build failed: Error: C:\projects\Handson\website1\node_modules\angular-4-data-table\src\index.ts is missing from the TypeScript compilation. Please make sure
it is in your tsconfig via the 'files' or 'include' property.
The missing file seems to be part of a third party library. TS files in published libraries are often a sign of a badly packaged library. Please open an issue in the library repository to alert its author and ask them to package the library using the Angular Package Format
at AngularCompilerPlugin.getCompiledFile (C:\projects\Handson\website1\node_modules\#ngtools\webpack\src\angular_compiler_plugin.js:656:23)
at plugin.done.then (C:\projects\Handson\website1\node_modules\#ngtools\webpack\src\loader.js:467:39)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
# ./src/app/display-table/display-table.component.ts 13:29-60
# ./src/app/app.module.ts
# ./src/main.ts
# multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts
It seems you are using angular 5 cli and need to integrate Angular 4 Data table on to your project.
My advice is to use angular5-data-table instead of version 4 if you are using angular 5.You can find it on https://www.npmjs.com/package/angular5-data-table

PrimeNG new Chart Release in R.C.1

I have update my primeNG to version to RC.1.
While doing so, I have made all the necessary changes required to run the application. Its been running fine.
Problem is that in this updated version, the Chart implementation has been changed.
Rather than using we have to use
After doing this change, I am not getting the component rendered on my browser. It is not giving any error in the console.
following is my code:
app.component.ts File:
import {Component} from '#angular/core';
import {HTTP_PROVIDERS} from '#angular/http';
import {InputText,DataTable,Button,Dialog,Column,Header,Footer} from 'primeng/primeng';
export class AppComponent {
data :any;
constructor(private carService: CarService) {
this.data = {
labels: ['A','B','C'],
datasets: [
{
data: [300, 50, 100],
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
};
}
}
app.conponent.html:
<div>
<p-chart type="pie" [data]="data"></p-chart>
</div>
Please help.
Thanks in Advance.