Print in Angular Grid component

25 Aug 202524 minutes to read

The printing feature in Syncfusion Grid allows you to easily generate and print a representation of the grid’s content for physical documentation and offline reference. You can enable this feature using either the grid’s toolbar or the programmatically available print method.

To add the printing option to the grid’s toolbar, include the toolbar property in your grid configuration and add Print as a toolbar item. This allows you to directly initiate the printing process when clicking on the Print item from the toolbar.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule, ToolbarService } from '@syncfusion/ej2-angular-grids'



import { Component, OnInit } from '@angular/core';
import { data } from './datasource';
import { ToolbarItems } from '@syncfusion/ej2-angular-grids';

@Component({
imports: [
        
        GridModule
    ],

providers: [ToolbarService],
standalone: true,
    selector: 'app-root',
    template: `<ejs-grid [dataSource]='data' [toolbar]='toolbarOptions' height='272px'>
                <e-columns>
                    <e-column field='OrderID' headerText='Order ID' textAlign='Right' width=120></e-column>
                    <e-column field='CustomerID' headerText='Customer ID' width=150></e-column>
                    <e-column field='ShipCity' headerText='Ship City' width=150></e-column>
                    <e-column field='ShipName' headerText='Ship Name' width=150></e-column>
                </e-columns>
                </ejs-grid>`
})
export class AppComponent implements OnInit {

    public data?: object[];
    public toolbarOptions?: ToolbarItems[];

    ngOnInit(): void {
        this.data = data;
        this.toolbarOptions = ['Print'];
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Page setup

When printing a webpage, print options such as layout, paper size, and margin settings cannot be configured through JavaScript code due to browser security restrictions. Instead, you need to customize these settings using the browser’s page setup dialog. Below are links to the page setup guides for popular web browsers:

You can print the grid’s content using an external button by utilizing the print method. This method allows you to trigger the printing process programmatically without requiring the built-in toolbar.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule, PageService } from '@syncfusion/ej2-angular-grids'
import { ButtonModule } from '@syncfusion/ej2-angular-buttons'



import { Component, OnInit, ViewChild } from '@angular/core';
import { data } from './datasource';
import { GridComponent } from '@syncfusion/ej2-angular-grids';

@Component({
imports: [
        
        GridModule, 
        ButtonModule
    ],

providers: [PageService],
standalone: true,
    selector: 'app-root',
    template: `<button ejs-button cssClass='e-primary' id='print' (click)='print()'>Print</button>
        <ejs-grid #grid [dataSource]='data' height='280px'>
            <e-columns>
                <e-column field='OrderID' headerText='Order ID' textAlign='Right' width=120></e-column>
                <e-column field='CustomerID' headerText='Customer ID' width=150></e-column>
                <e-column field='ShipCity' headerText='Ship City' width=150></e-column>
                <e-column field='ShipName' headerText='Ship Name' width=150></e-column>
            </e-columns>
        </ejs-grid>`
})
export class AppComponent implements OnInit {

    public data?: object[];

    @ViewChild('grid') public gridObj?: GridComponent;

    ngOnInit(): void {
        this.data = data;
    }

    print() {
        (this.gridObj as GridComponent).print();
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

By default, the Syncfusion Angular Grid prints all pages of the grid data. The printMode property allows you to control the printing scope. To print only the current visible page, set the printMode property to CurrentPage.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule, ToolbarService, PageService } from '@syncfusion/ej2-angular-grids'
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns'



import { Component, OnInit } from '@angular/core';
import { data } from './datasource';
import { ToolbarItems, PageSettingsModel } from '@syncfusion/ej2-angular-grids';
import { ChangeEventArgs } from '@syncfusion/ej2-angular-dropdowns';

@Component({
imports: [
        
        GridModule,
        DropDownListAllModule
    ],

providers: [ToolbarService, PageService],
standalone: true,
    selector: 'app-root',
    template: `<div style="display:flex;">
    <label style="padding: 10px 10px 26px 0">Select Print Mode </label>
    <ejs-dropdownlist
      style="margin-top:5px"
      id="value"
      #dropdown
      index="0"
      width="120"
      [dataSource]="dropdownlist"
      (change)="onChange($event)"
    ></ejs-dropdownlist></div>
                <ejs-grid [dataSource]='data' [printMode]='printMode' [allowPaging]='true'
               [pageSettings]='pageOptions' [toolbar]='toolbarOptions'>
                <e-columns>
                    <e-column field='OrderID' headerText='Order ID' textAlign='Right' width=120></e-column>
                    <e-column field='CustomerID' headerText='Customer ID' width=150></e-column>
                    <e-column field='ShipCity' headerText='Ship City' width=150></e-column>
                    <e-column field='ShipName' headerText='Ship Name' width=150></e-column>
                </e-columns>
                </ejs-grid>`
})
export class AppComponent implements OnInit {

    public data?: object[];
    public toolbarOptions?: ToolbarItems[];
    public pageOptions?: PageSettingsModel;
    public printMode: string = 'CurrentPage';
    public dropdownlist: string[] = ['AllPages', 'CurrentPage'];

    ngOnInit(): void {
        this.data = data;
        this.toolbarOptions = ['Print'];
        this.pageOptions = { pageSize: 6 };
    }
    onChange(args: ChangeEventArgs): void {
        this.printMode = args.value;
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

By default, the Syncfusion Angular Grid prints all data bound to its dataSource. However, you can print only the selected records from the grid by handling the beforePrint event, where you can replace the rows of the printing grid with the selected rows.

The following example demonstrates how to print only the selected records from the Angular Grid:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule, ToolbarService, PageService } from '@syncfusion/ej2-angular-grids'



import { Component, OnInit, ViewChild } from '@angular/core';
import { data } from './datasource';
import { GridComponent, PrintEventArgs, ToolbarItems, PageSettingsModel, SelectionSettingsModel } from '@syncfusion/ej2-angular-grids';
import { createElement } from '@syncfusion/ej2-base';

@Component({
imports: [
        
        GridModule
    ],

providers: [ToolbarService, PageService],
standalone: true,
    selector: 'app-root',
    template: `<ejs-grid #grid id='grid' [dataSource]='data' [allowPaging]='true'
               [pageSettings]='pageOptions' [selectionSettings]="selectionSettings" (beforePrint)='beforePrint($event)' [toolbar]='toolbarOptions'>
                <e-columns>
                    <e-column field='OrderID' headerText='Order ID' textAlign='Right' width=120></e-column>
                    <e-column field='CustomerID' headerText='Customer ID' width=150></e-column>
                    <e-column field='ShipCity' headerText='Ship City' width=150></e-column>
                    <e-column field='ShipName' headerText='Ship Name' width=150></e-column>
                </e-columns>
                </ejs-grid>`
})
export class AppComponent implements OnInit {

    @ViewChild('grid', { static: true })
    public grid?: GridComponent;
    public data?: object[];
    public toolbarOptions?: ToolbarItems[];
    public pageOptions?: PageSettingsModel;
    public selectionSettings?: SelectionSettingsModel;

    ngOnInit(): void {
        this.data = data;
        this.toolbarOptions = ['Print'];
        this.pageOptions = { pageSize: 6 };
        this.selectionSettings = { type: 'Multiple' }
    }
    beforePrint(e: PrintEventArgs): void {
        var rows = (this.grid as GridComponent).getSelectedRows();
        if (rows.length) {
            (e.element as CustomElement).ej2_instances[0].getContent().querySelector('tbody').remove();
            var tbody = createElement('tbody');
            rows = [...rows];
            for (var r = 0; r < rows.length; r++) {
                tbody.appendChild(rows[r].cloneNode(true));
            }
            (e.element as CustomElement).ej2_instances[0].getContentTable().appendChild(tbody);
        }
    }
}
interface CustomElement extends Element {
    ej2_instances: any[];
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

The Syncfusion Angular Grid supports printing hierarchy grids, which consist of a parent grid and its child grids. By default, when you print a hierarchy grid, it includes the parent grid and expanded child grids only. You can customize the print behavior using the hierarchyPrintMode property.

The hierarchyPrintMode property allows you to control the printing behavior for hierarchy grids. You can choose from three options:

Mode Behavior
Expanded Prints the parent grid with expanded child grids.
All Prints the parent grid with all the child grids, whether expanded or collapsed.
None Prints the parent grid alone.
import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule } from '@syncfusion/ej2-angular-grids'
import { DetailRowService, GridModel, ToolbarService, GridComponent } from '@syncfusion/ej2-angular-grids'
import { DropDownListAllModule,ChangeEventArgs} from '@syncfusion/ej2-angular-dropdowns'
import { Component, OnInit, ViewChild } from '@angular/core';
import { data, employeeData } from './datasource';

@Component({
    imports: [ GridModule,DropDownListAllModule],
    providers: [DetailRowService,ToolbarService],
    standalone: true,
    selector: 'app-root',
    template: `<div class='container'><h4>Select Mode</h4>
        <ejs-dropdownlist style="margin: 14px; width:250px; "  #sample [dataSource]='dropdownData' (change)='onModeChange($event)' popupHeight='220px'></ejs-dropdownlist></div>
        <ejs-grid #grid [dataSource]='parentData' height='265px' [childGrid]='childGrid' [toolbar]='["Print"]' [hierarchyPrintMode]='hierarchyPrintMode'>
            <e-columns>
                <e-column field='EmployeeID' headerText='Employee ID' textAlign='Right' width=120></e-column>
                <e-column field='FirstName' headerText='FirstName' width=150></e-column>
                <e-column field='LastName' headerText='Last Name' width=150></e-column>
                <e-column field='City' headerText='City' width=150></e-column>
            </e-columns>
        </ejs-grid>
                `
    })
export class AppComponent implements OnInit {

    public parentData?: object[];
    public dropdownData?: string[] = ['All', 'Expanded', 'None'];
    public hierarchyPrintMode: string = 'All';
    public childGrid: GridModel = {
        dataSource: data,
        queryString: 'EmployeeID',
        columns: [
            { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120 },
            { field: 'CustomerID', headerText: 'Customer ID', width: 150 },
            { field: 'ShipCity', headerText: 'Ship City', width: 150 },
            { field: 'ShipName', headerText: 'Ship Name', width: 150 }
        ],
    };
    @ViewChild('grid')
    public grid?: GridComponent;

    ngOnInit(): void {
        this.parentData = employeeData;
    }
    onModeChange(args: ChangeEventArgs): void {
        this.hierarchyPrintMode = args.value as string;
    }

}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

The Syncfusion Angular Grid provides the option to visualize details of a record in another grid in a master-detail manner. By default, when you print a master-detail grid, only the master grid is included in the print output. You can customize the print behavior to include both the master and detail grids using the beforePrint event of the grid.

The beforePrint event triggers before the actual printing process begins. You can handle this event to customize the print output. By adding the detail grid to the element argument of the beforePrint event, you can ensure that both the master and detail grids are printed on the page.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule, ToolbarService } from '@syncfusion/ej2-angular-grids'

import { Component, OnInit, ViewChild } from '@angular/core';
import { data, customerData } from './datasource';
import { GridComponent, ToolbarItems, RowSelectEventArgs, PrintEventArgs } from '@syncfusion/ej2-angular-grids';

@Component({
imports: [
        
        GridModule
    ],

providers: [ToolbarService],
standalone: true,
    selector: 'app-root',
    template: `<ejs-grid #mastergrid id="mastergrid" [dataSource]='masterdata' [selectedRowIndex]="1" [toolbar]='toolbar' (rowSelected)="onRowSelected($event)" (beforePrint)="beforePrint($event)">
        <e-columns>
            <e-column field='ContactName' headerText='Customer Name' width='150'></e-column>
            <e-column field='CompanyName' headerText='Company Name' width='150'></e-column>
            <e-column field='Address' headerText='Address' width='150'></e-column>
            <e-column field='Country' headerText='Country' width='130'></e-column>
        </e-columns>
    </ejs-grid>

    <div class='e-statustext' style="margin:8px">Showing orders of Customer: <b id="key"></b></div>
    
    <ejs-grid #detailgrid id="detailgrid" [dataSource]='data' [allowSelection]='false'>
        <e-columns>
            <e-column field='OrderID' headerText='Order ID' width='100'></e-column>
            <e-column field='Freight' headerText='Freight' format='C2' width='100' type='number'></e-column>
            <e-column field='ShipName' headerText="Ship Name" width='150'></e-column>
            <e-column field='ShipCountry' headerText="Ship Country" width='150'></e-column>
            <e-column field='ShipAddress' headerText="Ship Address" width='150'></e-column>
        </e-columns>
    </ejs-grid>`
})
export class AppComponent implements OnInit {

    public names?: string[] = ['AROUT', 'BERGS', 'BLONP', 'CHOPS', 'ERNSH'];
    public toolbar?: ToolbarItems[];

    @ViewChild('mastergrid') public mastergrid?: GridComponent;
    @ViewChild('detailgrid') public detailgrid?: GridComponent;

    public masterdata?: Object[];

    public data: object[] = data;

    ngOnInit(): void {
        this.masterdata = customerData.filter((e: object) => (this.names as string[]).indexOf((e as ItemType).CustomerID) !== -1);

        this.toolbar = ['Print'];
    }
    public onRowSelected(args: RowSelectEventArgs): void {
        let selectedRecord: object = args.data as object;
        (this.detailgrid as GridComponent).dataSource = data.filter((record: object) => (record as ItemType).CustomerName === (selectedRecord as ItemType).ContactName).slice(0, 5);
        (document.getElementById('key') as Element).innerHTML = (selectedRecord as ItemType).ContactName;
    }
    public beforePrint(args: PrintEventArgs): void {
        let customElement = document.createElement('div');
        customElement.innerHTML = document.getElementsByClassName('e-statustext')[0].innerHTML + (this.detailgrid as GridComponent).element.innerHTML;
        customElement.appendChild(document.createElement('br'));
        (args.element as Element).append(customElement);
    }
}
interface ItemType{
    CustomerName:string,
    CustomerID:string,
    ContactName:string
  }
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

When printing a grid with a large number of columns, the browser’s default page size (usually A4) might not be sufficient to display all columns properly. As a result, the browser’s print preview may automatically hide the overflowed content, leading to a cut-off appearance.

To display all columns when printing, you can adjust the scale option from the print option panel based on your content size. This allows you to fit the entire grid content within the printable area.

Scale Option Setting

Show or hide columns during printing

In the Syncfusion Angular Grid, you have the flexibility to control column visibility during the printing process. You can dynamically show or hide specific columns using the toolbarClick and printComplete events. This capability allows you to tailor the printed grid to your specific requirements.

In the toolbarClick event, you can show or hide columns by setting the column.visible property to true or false respectively.

In the printComplete event, the column visibility state is reset back to its original configuration.

The following example demonstrates how to show a hidden column (CustomerID) and hide a visible column (ShipCity) during printing and then reset their visibility after printing:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule, ToolbarService, PageService } from '@syncfusion/ej2-angular-grids'



import { Component, OnInit, ViewChild } from '@angular/core';
import { data } from './datasource';
import {ClickEventArgs} from '@syncfusion/ej2-inputs'
import { ToolbarItems, PageSettingsModel, GridComponent, Column } from '@syncfusion/ej2-angular-grids';


@Component({
imports: [
        
        GridModule
    ],

providers: [ToolbarService, PageService],
standalone: true,
    selector: 'app-root',
    template: `<ejs-grid #grid id='Grid' [dataSource]='data' (toolbarClick)='toolbarClick($event)' (printComplete)='printComplete()'
                [allowPaging]='true' [pageSettings]='pageOptions' [toolbar]='toolbarOptions'>
                <e-columns>
                    <e-column field='OrderID' headerText='Order ID' textAlign='Right' width=120></e-column>
                    <e-column field='CustomerID' headerText='Customer ID' [visible]= 'false' width=150></e-column>
                    <e-column field='ShipCity' headerText='Ship City' width=150></e-column>
                    <e-column field='ShipName' headerText='Ship Name' width=150></e-column>
                </e-columns>
                </ejs-grid>`
})
export class AppComponent implements OnInit {

    public data?: object[];
    public toolbarOptions?: ToolbarItems[];
    public pageOptions?: PageSettingsModel;
    @ViewChild('grid')
    public grid?: GridComponent;
    toolbarClick(args:ClickEventArgs) {
        if(args.item.id== 'Grid_print'){
            for (const columns of (this.grid as GridComponent).columns) {
                if ((columns as Column).field === 'CustomerID') {
                    (columns as Column).visible = true;
                } else if ((columns as Column).field === 'ShipCity') {
                    (columns as Column).visible = false;
                }
            }
        }
    }

    printComplete() {
        for (const columns of (this.grid as GridComponent).columns) {
            if ((columns as Column).field === 'CustomerID') {
                (columns as Column).visible = false;
            } else if ((columns as Column).field === 'ShipCity') {
                (columns as Column).visible = true;
            }
        }
    }

    ngOnInit(): void {
        this.data = data;
        this.toolbarOptions = ['Print'];
        this.pageOptions = { pageSize: 6 };
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Add title to print header

You can add a title to the header when printing the Syncfusion Grid by utilizing the beforePrint event. This event allows you to customize the print layout, including the addition of a title element, ensuring that the printed document is informative and visually appealing.

The following example shows how to add a title to your Grid when using the print function:

import { GridModule, ToolbarService ,PrintEventArgs} from '@syncfusion/ej2-angular-grids'
import { Component, OnInit } from '@angular/core';
import { data } from './datasource';
import { ToolbarItems } from '@syncfusion/ej2-angular-grids';

@Component({
imports: [ GridModule],
providers: [ToolbarService],
standalone: true,
    selector: 'app-root',
    template: `<ejs-grid [dataSource]='data' [toolbar]='toolbarOptions' height='272px' (beforePrint)="beforePrint($event)">
                <e-columns>
                    <e-column field='OrderID' headerText='Order ID' textAlign='Right' width=120></e-column>
                    <e-column field='CustomerID' headerText='Customer ID' width=150></e-column>
                    <e-column field='ShipCity' headerText='Ship City' width=150></e-column>
                    <e-column field='ShipName' headerText='Ship Name' width=150></e-column>
                </e-columns>
                </ejs-grid>`
})
export class AppComponent implements OnInit {

    public data?: object[];
    public toolbarOptions?: ToolbarItems[];

    ngOnInit(): void {
        this.data = data;
        this.toolbarOptions = ['Print'];
    }
    beforePrint(args:PrintEventArgs){
        var div = document.createElement("Div")
            div.innerHTML = "Title here"
            div.style.textAlign = 'center';
            div.style.color = 'red';
            div.style.padding = '10px 0';
            div.style.fontSize = '25px';
            (args.element as HTMLElement).insertBefore(div, (args.element as HTMLElement).childNodes[0]);
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Limitations when printing large datasets

Printing a large volume of data all at once in the grid can have certain limitations due to potential browser performance issues. Rendering numerous DOM elements on a single page can lead to browser slowdowns or even hang the browser. The grid offers a solution to manage extensive datasets through virtualization. However, virtualization for both rows and columns is not feasible during the printing process.

If printing all data remains a requirement, an alternative approach is recommended. Exporting the grid data to formats like Excel, CSV, or PDF is advised. This exported data can then be printed using non-web-based applications, mitigating the potential performance challenges associated with printing large datasets directly from the browser.

Retain grid styles while printing

The Syncfusion Angular Grid provides a beforePrint event that allows you to customize the appearance and styles of the grid before it is sent to the printer. By handling this event, you can ensure that the grid retains its styles and appearance during the printing process.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule, ToolbarService, PageService } from '@syncfusion/ej2-angular-grids'
import { Component, OnInit, ViewChild } from '@angular/core';
import { data } from './datasource';
import { ToolbarItems, PageSettingsModel, GridComponent } from '@syncfusion/ej2-angular-grids';

@Component({
imports: [ GridModule],
providers: [ToolbarService, PageService],
standalone: true,
    selector: 'app-root',
    template: `<ejs-grid #grid [dataSource]='data' (beforePrint)='beforePrint()'
                [allowPaging]='true' [pageSettings]='pageOptions' [toolbar]='toolbarOptions'>
                <e-columns>
                    <e-column field='OrderID' headerText='Order ID' textAlign='Right' width=120></e-column>
                    <e-column field='CustomerID' headerText='Customer ID' width=150></e-column>
                    <e-column field='ShipCity' headerText='Ship City' width=150></e-column>
                    <e-column field='ShipName' headerText='Ship Name' width=150></e-column>
                </e-columns>
                </ejs-grid>`,
    styleUrls: ['app.component.css'],
})
export class AppComponent implements OnInit {

    public data?: object[];
    public toolbarOptions?: ToolbarItems[];
    public pageOptions?: PageSettingsModel;
    @ViewChild('grid')
    public grid?: GridComponent;

    ngOnInit(): void {
        this.data = data;
        this.toolbarOptions = ['Print'];
        this.pageOptions = { pageSize: 6 };
    }
    beforePrint() {
        var styleElement = document.createElement('style');
        styleElement.innerHTML = `
        .e-grid .e-headercell {
            background: #24a0ed !important;
        }
        .e-grid .e-row .e-rowcell {
            background: #cbecff !important;
        }
        .e-grid .e-altrow .e-rowcell{
            background: #e7d7f7 !important;
        }
        `;
        (document.querySelector('head') as Element).appendChild(styleElement);
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

To print the Syncfusion Angular Grid along with another component, such as a chart, you can use the beforePrint event of the grid. In this event, you can clone the content of the other component and append it to the print document.

The following example shows how to print grid along with chart component:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { ChartModule } from '@syncfusion/ej2-angular-charts'
import { GridModule } from '@syncfusion/ej2-angular-grids'
import { AccumulationChartModule } from '@syncfusion/ej2-angular-charts'
import { ButtonModule } from '@syncfusion/ej2-angular-buttons'
import { PieSeriesService, AccumulationTooltipService, AccumulationDataLabelService } from '@syncfusion/ej2-angular-charts'
import { LineSeriesService, DateTimeService, DataLabelService,StackingColumnSeriesService,CategoryService,
       StepAreaSeriesService,SplineSeriesService, ChartAnnotationService, LegendService, TooltipService, StripLineService,
       SelectionService,ScatterSeriesService
    } from '@syncfusion/ej2-angular-charts'

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ChartComponent } from '@syncfusion/ej2-angular-charts';
import { GridComponent,PageService, ActionEventArgs, PrintEventArgs } from '@syncfusion/ej2-angular-grids';
import { Query, DataManager } from '@syncfusion/ej2-data';
import { orderData } from './datasource';

@Component({
    imports: [ ChartModule, AccumulationChartModule, GridModule,ButtonModule],

    providers: [ LineSeriesService, DateTimeService, DataLabelService, StackingColumnSeriesService,CategoryService,
                StepAreaSeriesService, SplineSeriesService, ChartAnnotationService, LegendService, TooltipService, StripLineService,
                PieSeriesService, AccumulationTooltipService, AccumulationDataLabelService, SelectionService,ScatterSeriesService
                ,PageService],
    standalone: true,
    selector: 'app-root',
    template: `
        <button class ='printbtn' ejs-button cssClass="e-danger" (click)="onClick()"> Print </button>
        <ejs-grid #grid
            [dataSource]="data"
            [allowPaging]="true"
            [pageSettings]="pageSettings"
            printMode="CurrentPage"
            (dataBound)="dataBound()"
            (actionComplete)="actionComplete($event)"
            (beforePrint)="beforePrint($event)">
            <e-columns>
                <e-column field="OrderDate" headerText="Order Date" width="130" format="yMd" textAlign="right"></e-column>
                <e-column field="Freight" width="120" format="C2" textAlign="right"></e-column>
            </e-columns>
        </ejs-grid>
        <h4>Chart</h4>
        <div #chartContainer >
            <ejs-chart #chart id="chart-container"
                [primaryXAxis]="primaryXAxis"
                [primaryYAxis]="primaryYAxis"
                [title]="title">
                width="60%"
                <e-series-collection>
                    <e-series type="Line" xName="OrderDate" yName="Freight"  width="1" columnWidth="0.4" name="dataview" [marker]="marker"></e-series>
                </e-series-collection>
            </ejs-chart>
        </div>
    `
})
export class AppComponent implements OnInit {
    public primaryXAxis?: Object;
    public chartData?: Object[];
    public data?: Object[];
    public title?: string;
    public marker?: Object;
    public primaryYAxis?: Object;
    public pageSettings?: Object;

    @ViewChild('chart') public chart?: ChartComponent;
    @ViewChild('grid') public grid?: GridComponent;
    @ViewChild('chartContainer') public chartContainer?: ElementRef;

    ngOnInit(): void {
        this.data = new DataManager(orderData as JSON[]).executeLocal(new Query().take(100));
        this.pageSettings = { pageSize: 10 };
    }

    dataBound() {
        this.chart!.primaryXAxis = {
            valueType: 'DateTime',
        };
        this.chart!.series[0].marker = { visible: true };
        this.chart!.series[0].xName = 'OrderDate';
        this.chart!.series[0].yName = 'Freight';
        this.chart!.series[0].dataSource = (this.grid as GridComponent).getCurrentViewRecords();
    }

    onClick() {
        (this.grid as GridComponent).print();
    }
    beforePrint(args: PrintEventArgs) {
        if (this.chartContainer) {
            const clonedChartContainer = this.chartContainer.nativeElement.cloneNode(true);
            (args.element as Element).appendChild(clonedChartContainer);
        }
    }
    public actionComplete(args: ActionEventArgs): void {
        if (args.requestType === 'paging') {
            this.chart!.series[0].dataSource = (this.grid as GridComponent).getCurrentViewRecords();
            this.chart?.refresh();
        }
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));