---
title: "Creating a Basic Grid"
framework: angular
version: "36.1.0"
---

# Creating a Basic Grid

Learn how to create and configure an AG Grid instance from scratch. This guide introduces the essential concepts required to build an interactive grid, including setting up row data, defining columns, applying grid options, formatting cell values, and adding custom components.

## Overview

In this tutorial you will:

1. [Create a basic grid](https://www.ag-grid.com/angular-data-grid/deep-dive/#create-a-basic-grid)
2. [Load external data into the grid](https://www.ag-grid.com/angular-data-grid/deep-dive/#load-new-data)
3. [Configure columns](https://www.ag-grid.com/angular-data-grid/deep-dive/#configure-columns)
4. [Configure grid features](https://www.ag-grid.com/angular-data-grid/deep-dive/#configure-the-grid)
5. [Format cell values](https://www.ag-grid.com/angular-data-grid/deep-dive/#format-cell-values)
6. [Add custom components to cells](https://www.ag-grid.com/angular-data-grid/deep-dive/#custom-cell-components)
7. [Hook into grid events](https://www.ag-grid.com/angular-data-grid/deep-dive/#handle-grid-events)

Once complete, you'll have an interactive grid, with custom components and formatted data - Try it out for yourself by **sorting**, **filtering**, **resizing**, **selecting**, or **editing** data in the grid:

#### Testing Example

```ts
import { HttpClient } from "@angular/common/http";
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  signal,
} from "@angular/core";

import type { ICellRendererAngularComp } from "ag-grid-angular";
import { AgGridAngular } from "ag-grid-angular";
import type {
  CellValueChangedEvent,
  ColDef,
  GridReadyEvent,
  ICellRendererParams,
  RowSelectionOptions,
  SelectionChangedEvent,
  ValueFormatterParams,
} from "ag-grid-community";
import {
  AllCommunityModule,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([AllCommunityModule]);

// Row Data Interface
interface IRow {
  mission: string;
  company: string;
  location: string;
  date: string;
  time: string;
  rocket: string;
  price: number;
  successful: boolean;
}

// Custom Cell Renderer Component
@Component({
  selector: "app-mission-result-renderer",
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  template: `
    <span>
      @if (value()) {
        <img
          [alt]="value()"
          [src]="
            'https://www.ag-grid.com/example-assets/icons/' + value() + '.png'
          "
          [height]="30"
        />
      }
    </span>
  `,
  styles: [
    "img { width: auto; height: auto; } span {display: flex; height: 100%; justify-content: center; align-items: center} ",
  ],
})
export class MissionResultRenderer implements ICellRendererAngularComp {
  value = signal("");
  agInit(params: ICellRendererParams): void {
    this.refresh(params);
  }

  refresh(params: ICellRendererParams): boolean {
    this.value.set(params.value ? "tick-in-circle" : "cross-in-circle");
    return true;
  }
}

// Custom Cell Renderer Component
@Component({
  selector: "app-company-logo-renderer",
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  template: `
    <span>
      @if (value()) {
        <img
          [alt]="value()"
          [src]="
            'https://www.ag-grid.com/example-assets/space-company-logos/' +
            lowercase() +
            '.png'
          "
        />
        <p>{{ value() }}</p>
      }
    </span>
  `,
  styles: [
    "img {display: block; width: 25px; height: auto; max-height: 50%; margin-right: 12px; filter: brightness(1.2);} span {display: flex; height: 100%; width: 100%; align-items: center} p { text-overflow: ellipsis; overflow: hidden; white-space: nowrap }",
  ],
})
export class CompanyLogoRenderer implements ICellRendererAngularComp {
  value = signal("");
  lowercase = computed(() => this.value().toLowerCase());

  agInit(params: ICellRendererParams): void {
    this.refresh(params);
  }

  refresh(params: ICellRendererParams): boolean {
    this.value.set(params.value);
    return true;
  }
}

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular],
  template: `
    <div class="content">
      <!-- The AG Grid component, with various Grid Option properties -->
      <ag-grid-angular
        style="width: 100%; height: 550px;"
        [rowData]="rowData"
        [columnDefs]="colDefs"
        [defaultColDef]="defaultColDef"
        [pagination]="true"
        [rowSelection]="rowSelection"
        (gridReady)="onGridReady($event)"
        (cellValueChanged)="onCellValueChanged($event)"
        (selectionChanged)="onSelectionChanged($event)"
      />
    </div>
  `,
})
export class AppComponent {
  // Return formatted date value
  dateFormatter(params: ValueFormatterParams) {
    return new Date(params.value).toLocaleDateString("en-us", {
      weekday: "long",
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  }

  // Row Data: The data to be displayed.
  rowData: IRow[] = [];

  // Column Definitions: Defines & controls grid columns.
  colDefs: ColDef[] = [
    {
      field: "mission",
      width: 150,
    },
    {
      field: "company",
      width: 130,
      cellRenderer: CompanyLogoRenderer,
    },
    {
      field: "location",
      width: 225,
    },
    {
      field: "date",
      valueFormatter: this.dateFormatter,
    },
    {
      field: "price",
      width: 130,
      valueFormatter: (params) => {
        return "£" + params.value.toLocaleString();
      },
    },
    {
      field: "successful",
      width: 120,
      cellRenderer: MissionResultRenderer,
    },
    { field: "rocket" },
  ];

  rowSelection: RowSelectionOptions = {
    mode: "multiRow",
    headerCheckbox: false,
  };

  // Default Column Definitions: Apply configuration across all columns
  defaultColDef: ColDef = {
    filter: true, // Enable filtering on all columns
    editable: true, // Enable editing on all columns
  };

  // Load data into grid when ready
  constructor(private http: HttpClient) {}
  onGridReady(params: GridReadyEvent) {
    this.http
      .get<
        any[]
      >("https://www.ag-grid.com/example-assets/space-mission-data.json")
      .subscribe((data) => (this.rowData = data));
  }

  // Handle row selection changed event
  onSelectionChanged = (event: SelectionChangedEvent) => {
    console.log("Row Selected!");
  };

  // Handle cell editing event
  onCellValueChanged = (event: CellValueChangedEvent) => {
    console.log(`New Cell Value: ${event.value}`);
  };
}
```

[Live example: Testing Example](https://www.ag-grid.com/examples/deep-dive/testing-example/angular)

## Create a Basic Grid

Complete our [Quick Start](https://www.ag-grid.com/angular-data-grid/getting-started/) (or open the example below in CodeSandbox / Plunker) to start with a basic grid, comprised of:

1. **Row Data:** The data to be displayed.
2. **Column Definition:** Defines & controls grid columns.
3. **Grid Component:** The `ag-grid-angular` component, with Dimensions, Row Data, and Column Definition attributes

#### Basic Example

```ts
import { Component } from "@angular/core";

import { AgGridAngular } from "ag-grid-angular";
import type { ColDef } from "ag-grid-community";
import {
  AllCommunityModule,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([AllCommunityModule]);

// Row Data Interface
interface IRow {
  make: string;
  model: string;
  price: number;
  electric: boolean;
}

@Component({
  standalone: true,
  imports: [AgGridAngular],
  selector: "my-app",
  template: `
    <div class="content">
      <!-- The AG Grid component, with Dimensions, CSS Theme, Row Data, and Column Definition -->
      <ag-grid-angular
        style="width: 100%; height: 220px;"
        [rowData]="rowData"
        [columnDefs]="colDefs"
      />
    </div>
  `,
})
export class AppComponent {
  // Row Data: The data to be displayed.
  rowData: IRow[] = [
    { make: "Tesla", model: "Model Y", price: 64950, electric: true },
    { make: "Ford", model: "F-Series", price: 33850, electric: false },
    { make: "Toyota", model: "Corolla", price: 29600, electric: false },
  ];

  // Column Definitions: Defines & controls grid columns.
  colDefs: ColDef<IRow>[] = [
    { field: "make" },
    { field: "model" },
    { field: "price" },
    { field: "electric" },
  ];
}
```

[Live example: Basic Example](https://www.ag-grid.com/examples/deep-dive/basic-example/angular)

## Load New Data

As rowData is a managed property, any updates to its value will be reflected in the grid. Let's test this by fetching some data from an external server with [Angular's HttpClient](https://angular.dev/guide/http) and updating rowData with the response.

First we need to hook into the `gridReady` event by adding `(gridReady)="onGridReady($event)"` to the `ag-grid-angular` component:

```html
<!-- The AG Grid component, with various Grid Option properties -->
<ag-grid-angular
    style="width: 100%; height: 550px;"
    [rowData]="rowData"
    [columnDefs]="colDefs"
    (gridReady)="onGridReady($event)"
/>
```

*Note: [Grid Events](https://www.ag-grid.com/angular-data-grid/deep-dive/#handle-grid-events) are covered in more detail later on*

And then executing a HTTP request when the onGridReady event is fired, subscribing to the result to update our rowData asynchronously:

```ts
// Load data into grid when ready
onGridReady(params: GridReadyEvent) {
    this.http
        .get<any[]>('https://www.ag-grid.com/example-assets/space-mission-data.json')
        .subscribe(data => this.rowData = data);
}
```

Finally, now that we're loading data from an external source, we can empty our `rowData` array (which will allow the grid to display a loading spinner whilst the data is being fetched) and update our `colDefs` to match the new dataset:

```jsx
export class AppComponent {
    // Row Data: The data to be displayed.
    rowData: IRow[] = [];
    colDefs: ColDef[] = [
        { field: "mission" },
        { field: "company" },
        { field: "location" },
        { field: "date" },
        { field: "price" },
        { field: "successful" },
        { field: "rocket" }
    ];
    // ...
}
```

When we run our application, we should see a grid with ~1,400 rows of new data, and new column headers to match:

#### Updating Example

```ts
import { HttpClient } from "@angular/common/http";
import { Component } from "@angular/core";

import { AgGridAngular } from "ag-grid-angular";
import type { ColDef, GridReadyEvent } from "ag-grid-community";
import {
  AllCommunityModule,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([AllCommunityModule]);

// Row Data Interface
interface IRow {
  mission: string;
  company: string;
  location: string;
  date: string;
  time: string;
  rocket: string;
  price: number;
  successful: boolean;
}

@Component({
  standalone: true,
  imports: [AgGridAngular],
  selector: "my-app",
  template: `
    <div class="content">
      <!-- The AG Grid component, with Dimensions, CSS Theme, Row Data, and Column Definition -->
      <ag-grid-angular
        style="width: 100%; height: 550px;"
        [rowData]="rowData"
        [columnDefs]="colDefs"
        (gridReady)="onGridReady($event)"
      />
    </div>
  `,
})
export class AppComponent {
  // Row Data: The data to be displayed.
  rowData: IRow[] = [];

  // Column Definitions: Defines & controls grid columns.
  colDefs: ColDef[] = [
    { field: "mission" },
    { field: "company" },
    { field: "location" },
    { field: "date" },
    { field: "price" },
    { field: "successful" },
    { field: "rocket" },
  ];

  // Load data into grid when ready
  constructor(private http: HttpClient) {}
  onGridReady(params: GridReadyEvent) {
    this.http
      .get<
        any[]
      >("https://www.ag-grid.com/example-assets/space-mission-data.json")
      .subscribe((data) => (this.rowData = data));
  }
}
```

[Live example: Updating Example](https://www.ag-grid.com/examples/deep-dive/updating-example/angular)

*Note: All [Grid Option](https://www.ag-grid.com/angular-data-grid/grid-options/) properties tagged as 'managed' are automatically updated when their value changes.*

## Configure Columns

Now that we have a basic grid with some arbitrary data, we can start to configure the grid with ***Column Properties***.

Column Properties can be added to one or more columns to enable/disable column-specific features. Let's try this by adding the `filter: true` property to the 'mission' column:

```jsx
colDefs: ColDef[] = [
    { field: "mission", filter: true },
    // ...
];
```

We should now be able to filter the 'mission' column - you can test this by filtering for the 'Apollo' missions:

#### Configuring Columns Example

```ts
import { HttpClient } from "@angular/common/http";
import { Component } from "@angular/core";

import { AgGridAngular } from "ag-grid-angular";
import type { ColDef, GridReadyEvent } from "ag-grid-community";
import {
  AllCommunityModule,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([AllCommunityModule]);

// Row Data Interface
interface IRow {
  mission: string;
  company: string;
  location: string;
  date: string;
  time: string;
  rocket: string;
  price: number;
  successful: boolean;
}

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular],
  template: `
    <div class="content">
      <!-- The AG Grid component, with Dimensions, CSS Theme, Row Data, and Column Definition -->
      <ag-grid-angular
        style="width: 100%; height: 550px;"
        [rowData]="rowData"
        [columnDefs]="colDefs"
        (gridReady)="onGridReady($event)"
      />
    </div>
  `,
})
export class AppComponent {
  // Row Data: The data to be displayed.
  rowData: IRow[] = [];

  // Column Definitions: Defines & controls grid columns.
  colDefs: ColDef[] = [
    { field: "mission", filter: true },
    { field: "company" },
    { field: "location" },
    { field: "date" },
    { field: "price" },
    { field: "successful" },
    { field: "rocket" },
  ];

  // Load data into grid when ready
  constructor(private http: HttpClient) {}
  onGridReady(params: GridReadyEvent) {
    this.http
      .get<
        any[]
      >("https://www.ag-grid.com/example-assets/space-mission-data.json")
      .subscribe((data) => (this.rowData = data));
  }
}
```

[Live example: Configuring Columns Example](https://www.ag-grid.com/examples/deep-dive/configure-columns-example/angular)

*Note: Column properties can be used to configure a wide-range of features; refer to our [Column Properties](https://www.ag-grid.com/angular-data-grid/column-properties/) page for a full list of features.*

### Default Column Definitions

The example above demonstrates how to configure a single column. To apply this configuration across all columns we can use ***Default Column Definitions*** instead. Let's make all of our columns filterable by creating a `defaultColDef` object, setting `filter: true`, and passing this to our template:

```jsx
@Component({
    template:
    `
    <div class="content">
        <ag-grid-angular
            ...
            [defaultColDef]="defaultColDef"
        />
    </div>
    `,
    // ...
})

export class AppComponent {
// Default Column Definitions: Apply configuration across all columns
defaultColDef: ColDef = {
        filter: true
    }
    // ...
}
```

The grid should now allow filtering on all columns:

#### Default Column Definitions Example

```ts
import { HttpClient } from "@angular/common/http";
import { Component } from "@angular/core";

import { AgGridAngular } from "ag-grid-angular";
import type { ColDef, GridReadyEvent } from "ag-grid-community";
import {
  AllCommunityModule,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([AllCommunityModule]);

// Row Data Interface
interface IRow {
  mission: string;
  company: string;
  location: string;
  date: string;
  time: string;
  rocket: string;
  price: number;
  successful: boolean;
}

@Component({
  standalone: true,
  imports: [AgGridAngular],
  selector: "my-app",
  template: `
    <div class="content">
      <!-- The AG Grid component, with Dimensions, CSS Theme, Row Data, and Column Definition -->
      <ag-grid-angular
        style="width: 100%; height: 550px;"
        [rowData]="rowData"
        [columnDefs]="colDefs"
        [defaultColDef]="defaultColDef"
        (gridReady)="onGridReady($event)"
      />
    </div>
  `,
})
export class AppComponent {
  // Row Data: The data to be displayed.
  rowData: IRow[] = [];

  // Column Definitions: Defines & controls grid columns.
  colDefs: ColDef[] = [
    { field: "mission" },
    { field: "company" },
    { field: "location" },
    { field: "date" },
    { field: "price" },
    { field: "successful" },
    { field: "rocket" },
  ];

  // Default Column Definitions: Apply configuration across all columns
  defaultColDef: ColDef = {
    filter: true,
  };

  // Load data into grid when ready
  constructor(private http: HttpClient) {}
  onGridReady(params: GridReadyEvent) {
    this.http
      .get<
        any[]
      >("https://www.ag-grid.com/example-assets/space-mission-data.json")
      .subscribe((data) => (this.rowData = data));
  }
}
```

[Live example: Default Column Definitions Example](https://www.ag-grid.com/examples/deep-dive/default-columns-example/angular)

*Note: Column Definitions take precedence over Default Column Definitions*

## Configure The Grid

So far we've covered creating a grid, updating the data within the grid, and configuring columns. This section introduces **Grid Options**, which control functionality that extends across both rows & columns, such as Pagination and Row Selection.

Grid Options are passed to the grid via attributes on the `ag-grid-angular` component. Let's enable pagination by adding `[pagination]="true"`:

```html
<!-- The AG Grid component, with various Grid Option properties -->
<ag-grid-angular
    ...
    [pagination]="true"
/>
```

We should now see Pagination has been enabled on the grid:

#### Grid Options Example

```ts
import { HttpClient } from "@angular/common/http";
import { Component } from "@angular/core";

import { AgGridAngular } from "ag-grid-angular";
import type { ColDef, GridReadyEvent } from "ag-grid-community";
import {
  AllCommunityModule,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([AllCommunityModule]);

// Row Data Interface
interface IRow {
  mission: string;
  company: string;
  location: string;
  date: string;
  time: string;
  rocket: string;
  price: number;
  successful: boolean;
}

@Component({
  standalone: true,
  selector: "my-app",
  imports: [AgGridAngular],
  template: `
    <div class="content">
      <!-- The AG Grid component, with Dimensions, CSS Theme, Row Data, and Column Definition -->
      <ag-grid-angular
        style="width: 100%; height: 550px;"
        [rowData]="rowData"
        [columnDefs]="colDefs"
        [defaultColDef]="defaultColDef"
        (gridReady)="onGridReady($event)"
        [pagination]="true"
      />
    </div>
  `,
})
export class AppComponent {
  // Row Data: The data to be displayed.
  rowData: IRow[] = [];

  // Column Definitions: Defines & controls grid columns.
  colDefs: ColDef[] = [
    { field: "mission", filter: true },
    { field: "company" },
    { field: "location" },
    { field: "date" },
    { field: "price" },
    { field: "successful" },
    { field: "rocket" },
  ];

  // Default Column Definitions: Apply configuration across all columns
  defaultColDef: ColDef = {
    filter: true,
  };

  // Load data into grid when ready
  constructor(private http: HttpClient) {}
  onGridReady(params: GridReadyEvent) {
    this.http
      .get<
        any[]
      >("https://www.ag-grid.com/example-assets/space-mission-data.json")
      .subscribe((data) => (this.rowData = data));
  }
}
```

[Live example: Grid Options Example](https://www.ag-grid.com/examples/deep-dive/grid-options-example/angular)

*Refer to our detailed [Grid Options](https://www.ag-grid.com/angular-data-grid/grid-options/) documentation for a full list of options.*

## Format Cell Values

The data supplied to the grid usually requires some degree of formatting. For basic text formatting we can use **Value Formatters**.

**Value Formatters** are basic functions which take the value of the cell, apply some basic formatting, and return a new value to be displayed by the grid. Let's try this by adding the `valueFormatter` property to our 'price' column and returning the formatted value:

```ts
colDefs: ColDef[] = [
    {
        field: "price",
        valueFormatter: params => { return '£' + params.value.toLocaleString(); } // Format with inline function
    },
    // ...
];
```

The grid should now show the formatted value in the 'price' column:

#### Value Formatter Example

```ts
import { HttpClient } from "@angular/common/http";
import { Component } from "@angular/core";

import { AgGridAngular } from "ag-grid-angular";
import type {
  ColDef,
  GridReadyEvent,
  ValueFormatterParams,
} from "ag-grid-community";
import {
  AllCommunityModule,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([AllCommunityModule]);

// Row Data Interface
interface IRow {
  mission: string;
  company: string;
  location: string;
  date: string;
  time: string;
  rocket: string;
  price: number;
  successful: boolean;
}

@Component({
  standalone: true,
  imports: [AgGridAngular],
  selector: "my-app",
  template: `
    <div class="content">
      <!-- The AG Grid component, with Dimensions, CSS Theme, Row Data, and Column Definition -->
      <ag-grid-angular
        style="width: 100%; height: 550px;"
        [rowData]="rowData"
        [columnDefs]="colDefs"
        [defaultColDef]="defaultColDef"
        (gridReady)="onGridReady($event)"
        [pagination]="true"
      />
    </div>
  `,
})
export class AppComponent {
  // Row Data: The data to be displayed.
  rowData: IRow[] = [];

  // Column Definitions: Defines & controls grid columns.
  colDefs: ColDef[] = [
    {
      field: "mission",
      filter: true,
    },
    { field: "company" },
    { field: "location" },
    { field: "date" },
    {
      field: "price",
      valueFormatter: (params: ValueFormatterParams) => {
        return "£" + params.value.toLocaleString();
      },
    },
    { field: "successful" },
    { field: "rocket" },
  ];

  // Default Column Definitions: Apply configuration across all columns
  defaultColDef: ColDef = {
    filter: true,
  };

  // Load data into grid when ready
  constructor(private http: HttpClient) {}
  onGridReady(params: GridReadyEvent) {
    this.http
      .get<
        any[]
      >("https://www.ag-grid.com/example-assets/space-mission-data.json")
      .subscribe((data) => (this.rowData = data));
  }
}
```

[Live example: Value Formatter Example](https://www.ag-grid.com/examples/deep-dive/value-formatter-example/angular)

*Note: Read our [Value Formatter](https://www.ag-grid.com/angular-data-grid/value-formatters/) page for more information on formatting cell values*

## Custom Cell Components

**Value Formatters** are useful for basic formatting, but for more advanced use-cases we can use **Cell Renderers** instead.

**Cell Renderers** allow you to use your own components within cells. To use a custom component, add the `cellRenderer` prop to a column and set the value to the name of your component.

Let's try this by creating a new component to display the company logo in the 'company' column:

```jsx
// Custom Cell Renderer Component
@Component({
    selector: 'app-company-logo-renderer',
    standalone: true,
    template: `<span>@if(value){<img [alt]="value" [src]="'https://www.ag-grid.com/example-assets/space-company-logos/' + value.toLowerCase() + '.png'" /> <p>{{ value }}</p>}</span>`,
    styles: ["img {display: block; width: 25px; height: auto; max-height: 50%; margin-right: 12px; filter: brightness(1.2);} span {display: flex; height: 100%; width: 100%; align-items: center} p { text-overflow: ellipsis; overflow: hidden; white-space: nowrap }"]
    })

    export class CompanyLogoRenderer implements ICellRendererAngularComp {
    // Init Cell Value
    public value!: string;
    agInit(params: ICellRendererParams): void {
        this.value = params.value;
    }

    refresh(params: ICellRendererParams): boolean {
        this.value = params.value;
        return true;
    }
}
```

And then adding the cellRenderer prop on our 'company' column to use our component:

```ts
colDefs: ColDef[] = [
    {
        field: "company",
        cellRenderer: CompanyLogoRenderer // Render a custom component
    }
    // ...
];
```

Now, when we run the grid, we should see a company logo next to the name:

#### Cell Renderer Example

```ts
import { HttpClient } from "@angular/common/http";
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  signal,
} from "@angular/core";

import type { ICellRendererAngularComp } from "ag-grid-angular";
import { AgGridAngular } from "ag-grid-angular";
import type {
  ColDef,
  GridReadyEvent,
  ICellRendererParams,
  ValueFormatterParams,
} from "ag-grid-community";
import {
  AllCommunityModule,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([AllCommunityModule]);

// Row Data Interface
interface IRow {
  mission: string;
  company: string;
  location: string;
  date: string;
  time: string;
  rocket: string;
  price: number;
  successful: boolean;
}

// Custom Cell Renderer Component
@Component({
  selector: "app-company-logo-renderer",
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  template: `
    <span>
      @if (value()) {
        <img
          [alt]="value()"
          [src]="
            'https://www.ag-grid.com/example-assets/space-company-logos/' +
            lowercase() +
            '.png'
          "
        />
        <p>{{ value() }}</p>
      }
    </span>
  `,
  styles: [
    "img {display: block; width: 25px; height: auto; max-height: 50%; margin-right: 12px; filter: brightness(1.2);} span {display: flex; height: 100%; width: 100%; align-items: center} p { text-overflow: ellipsis; overflow: hidden; white-space: nowrap }",
  ],
})
export class CompanyLogoRenderer implements ICellRendererAngularComp {
  value = signal("");
  lowercase = computed(() => this.value().toLowerCase());

  agInit(params: ICellRendererParams): void {
    this.value.set(params.value);
  }

  refresh(params: ICellRendererParams): boolean {
    this.value.set(params.value);
    return true;
  }
}

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular],
  template: `
    <div class="content">
      <!-- The AG Grid component, with Dimensions, CSS Theme, Row Data, and Column Definition -->
      <ag-grid-angular
        style="width: 100%; height: 550px;"
        [rowData]="rowData"
        [columnDefs]="colDefs"
        [defaultColDef]="defaultColDef"
        (gridReady)="onGridReady($event)"
        [pagination]="true"
      />
    </div>
  `,
})
export class AppComponent {
  // Row Data: The data to be displayed.
  rowData: IRow[] = [];

  // Column Definitions: Defines & controls grid columns.
  colDefs: ColDef[] = [
    {
      field: "mission",
      filter: true,
    },
    {
      field: "company",
      cellRenderer: CompanyLogoRenderer,
    },
    {
      field: "location",
    },
    { field: "date" },
    {
      field: "price",
      valueFormatter: (params: ValueFormatterParams) => {
        return "£" + params.value.toLocaleString();
      },
    },
    { field: "successful" },
    { field: "rocket" },
  ];

  // Default Column Definitions: Apply configuration across all columns
  defaultColDef: ColDef = {
    filter: true,
  };

  // Load data into grid when ready
  constructor(private http: HttpClient) {}
  onGridReady(params: GridReadyEvent) {
    this.http
      .get<
        any[]
      >("https://www.ag-grid.com/example-assets/space-mission-data.json")
      .subscribe((data) => (this.rowData = data));
  }
}
```

[Live example: Cell Renderer Example](https://www.ag-grid.com/examples/deep-dive/cell-renderer-example/angular)

*Note: Read our [Cell Components](https://www.ag-grid.com/angular-data-grid/component-cell-renderer/) page for more information on using custom components in cells*

## Handle Grid Events

In the last section of this tutorial we're going to hook into events raised by the grid using ***Grid Events***.

To be notified of when an event is raised by the grid we need to add the relevant event name attribute to the `ag-grid-angular` component.

Let's try this out by enabling cell editing with `editable: true` on the Default Column Definitions:

```ts
// Default Column Definitions: Apply configuration across all columns
defaultColDef: ColDef = {
    editable: true
    // ...
}
```

Next, lets create a function to handle the event:

```jsx
// Handle cell editing event
onCellValueChanged = (event: CellValueChangedEvent) => {
    console.log(`New Cell Value: ${event.value}`)
}
```

Finally, let's add the `cellValueChanged` attribute to the `ag-grid-angular` component, with the value as the function we've just created:

```ts
<!-- The AG Grid component, with various Grid Option properties -->
<ag-grid-angular
    (cellValueChanged)="onCellValueChanged($event)"
    ...
/>
```

Now, when we click on a cell we should be able to edit it and see the new value logged to the console:

#### Complete Example

```ts
import { HttpClient } from "@angular/common/http";
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  signal,
} from "@angular/core";

import type { ICellRendererAngularComp } from "ag-grid-angular";
import { AgGridAngular } from "ag-grid-angular";
import type {
  CellValueChangedEvent,
  ColDef,
  GridReadyEvent,
  ICellRendererParams,
  ValueFormatterParams,
} from "ag-grid-community";
import {
  AllCommunityModule,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([AllCommunityModule]);

// Row Data Interface
interface IRow {
  mission: string;
  company: string;
  location: string;
  date: string;
  time: string;
  rocket: string;
  price: number;
  successful: boolean;
}

// Custom Cell Renderer Component
@Component({
  selector: "app-company-logo-renderer",
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  template: `
    <span>
      @if (value()) {
        <img
          [alt]="value()"
          [src]="
            'https://www.ag-grid.com/example-assets/space-company-logos/' +
            lowercase() +
            '.png'
          "
        />
        <p>{{ value() }}</p>
      }
    </span>
  `,
  styles: [
    "img {display: block; width: 25px; height: auto; max-height: 50%; margin-right: 12px; filter: brightness(1.2);} span {display: flex; height: 100%; width: 100%; align-items: center} p { text-overflow: ellipsis; overflow: hidden; white-space: nowrap }",
  ],
})
export class CompanyLogoRenderer implements ICellRendererAngularComp {
  value = signal("");
  lowercase = computed(() => this.value().toLowerCase());

  agInit(params: ICellRendererParams): void {
    this.value.set(params.value);
  }

  refresh(params: ICellRendererParams): boolean {
    this.value.set(params.value);
    return true;
  }
}

@Component({
  standalone: true,
  imports: [AgGridAngular],
  selector: "my-app",
  template: `
    <div class="content">
      <!-- The AG Grid component, with Dimensions, CSS Theme, Row Data, and Column Definition -->
      <ag-grid-angular
        style="width: 100%; height: 550px;"
        [rowData]="rowData"
        [columnDefs]="colDefs"
        [defaultColDef]="defaultColDef"
        [pagination]="true"
        (gridReady)="onGridReady($event)"
        (cellValueChanged)="onCellValueChanged($event)"
      />
    </div>
  `,
})
export class AppComponent {
  // Row Data: The data to be displayed.
  rowData: IRow[] = [];

  // Column Definitions: Defines & controls grid columns.
  colDefs: ColDef[] = [
    {
      field: "mission",
      filter: true,
    },
    {
      field: "company",
      cellRenderer: CompanyLogoRenderer,
    },
    {
      field: "location",
    },
    { field: "date" },
    {
      field: "price",
      valueFormatter: (params: ValueFormatterParams) => {
        return "£" + params.value.toLocaleString();
      },
    },
    { field: "successful" },
    { field: "rocket" },
  ];

  // Default Column Definitions: Apply configuration across all columns
  defaultColDef: ColDef = {
    filter: true,
    editable: true,
  };

  // Handle cell editing event
  onCellValueChanged = (event: CellValueChangedEvent) => {
    console.log(`New Cell Value: ${event.value}`);
  };

  // Load data into grid when ready
  constructor(private http: HttpClient) {}
  onGridReady(params: GridReadyEvent) {
    this.http
      .get<
        any[]
      >("https://www.ag-grid.com/example-assets/space-mission-data.json")
      .subscribe((data) => (this.rowData = data));
  }
}
```

[Live example: Complete Example](https://www.ag-grid.com/examples/deep-dive/grid-events-example/angular)

*Refer to our [Grid Events](https://www.ag-grid.com/angular-data-grid/grid-events/) documentation for a full list of events raised by the grid*

## Test Your Knowledge

Let's put what you've learned so far into action by modifying the grid:

1. Enable filtering on all columns

   *Hint: `filter` is a Column Definition property*
2. Enable multiple row selection

   *Hint: `rowSelection` is a Grid Option property*
3. Log a message to the console when a row selection is changed

   *Hint: `onSelectionChanged` is a Grid Event*
4. Format the Date column using `.toLocaleDateString()`;

   *Hint: Use a `valueFormatter` on the 'Date' column to format its value*
5. Add a Cell Renderer to display [ticks](https://www.ag-grid.com/example-assets/icons/tick-in-circle.png) and [crosses](https://www.ag-grid.com/example-assets/icons/cross-in-circle.png) in place of checkboxes on the 'Successful' column:

   *Hint: Use a `cellRenderer` on the 'successful' column*

Once complete, your grid should look like the example below. If you're stuck, check out the source code to see how its done:

#### Testing Example

```ts
import { HttpClient } from "@angular/common/http";
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  signal,
} from "@angular/core";

import type { ICellRendererAngularComp } from "ag-grid-angular";
import { AgGridAngular } from "ag-grid-angular";
import type {
  CellValueChangedEvent,
  ColDef,
  GridReadyEvent,
  ICellRendererParams,
  RowSelectionOptions,
  SelectionChangedEvent,
  ValueFormatterParams,
} from "ag-grid-community";
import {
  AllCommunityModule,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([AllCommunityModule]);

// Row Data Interface
interface IRow {
  mission: string;
  company: string;
  location: string;
  date: string;
  time: string;
  rocket: string;
  price: number;
  successful: boolean;
}

// Custom Cell Renderer Component
@Component({
  selector: "app-mission-result-renderer",
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  template: `
    <span>
      @if (value()) {
        <img
          [alt]="value()"
          [src]="
            'https://www.ag-grid.com/example-assets/icons/' + value() + '.png'
          "
          [height]="30"
        />
      }
    </span>
  `,
  styles: [
    "img { width: auto; height: auto; } span {display: flex; height: 100%; justify-content: center; align-items: center} ",
  ],
})
export class MissionResultRenderer implements ICellRendererAngularComp {
  value = signal("");
  agInit(params: ICellRendererParams): void {
    this.refresh(params);
  }

  refresh(params: ICellRendererParams): boolean {
    this.value.set(params.value ? "tick-in-circle" : "cross-in-circle");
    return true;
  }
}

// Custom Cell Renderer Component
@Component({
  selector: "app-company-logo-renderer",
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  template: `
    <span>
      @if (value()) {
        <img
          [alt]="value()"
          [src]="
            'https://www.ag-grid.com/example-assets/space-company-logos/' +
            lowercase() +
            '.png'
          "
        />
        <p>{{ value() }}</p>
      }
    </span>
  `,
  styles: [
    "img {display: block; width: 25px; height: auto; max-height: 50%; margin-right: 12px; filter: brightness(1.2);} span {display: flex; height: 100%; width: 100%; align-items: center} p { text-overflow: ellipsis; overflow: hidden; white-space: nowrap }",
  ],
})
export class CompanyLogoRenderer implements ICellRendererAngularComp {
  value = signal("");
  lowercase = computed(() => this.value().toLowerCase());

  agInit(params: ICellRendererParams): void {
    this.refresh(params);
  }

  refresh(params: ICellRendererParams): boolean {
    this.value.set(params.value);
    return true;
  }
}

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular],
  template: `
    <div class="content">
      <!-- The AG Grid component, with various Grid Option properties -->
      <ag-grid-angular
        style="width: 100%; height: 550px;"
        [rowData]="rowData"
        [columnDefs]="colDefs"
        [defaultColDef]="defaultColDef"
        [pagination]="true"
        [rowSelection]="rowSelection"
        (gridReady)="onGridReady($event)"
        (cellValueChanged)="onCellValueChanged($event)"
        (selectionChanged)="onSelectionChanged($event)"
      />
    </div>
  `,
})
export class AppComponent {
  // Return formatted date value
  dateFormatter(params: ValueFormatterParams) {
    return new Date(params.value).toLocaleDateString("en-us", {
      weekday: "long",
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  }

  // Row Data: The data to be displayed.
  rowData: IRow[] = [];

  // Column Definitions: Defines & controls grid columns.
  colDefs: ColDef[] = [
    {
      field: "mission",
      width: 150,
    },
    {
      field: "company",
      width: 130,
      cellRenderer: CompanyLogoRenderer,
    },
    {
      field: "location",
      width: 225,
    },
    {
      field: "date",
      valueFormatter: this.dateFormatter,
    },
    {
      field: "price",
      width: 130,
      valueFormatter: (params) => {
        return "£" + params.value.toLocaleString();
      },
    },
    {
      field: "successful",
      width: 120,
      cellRenderer: MissionResultRenderer,
    },
    { field: "rocket" },
  ];

  rowSelection: RowSelectionOptions = {
    mode: "multiRow",
    headerCheckbox: false,
  };

  // Default Column Definitions: Apply configuration across all columns
  defaultColDef: ColDef = {
    filter: true, // Enable filtering on all columns
    editable: true, // Enable editing on all columns
  };

  // Load data into grid when ready
  constructor(private http: HttpClient) {}
  onGridReady(params: GridReadyEvent) {
    this.http
      .get<
        any[]
      >("https://www.ag-grid.com/example-assets/space-mission-data.json")
      .subscribe((data) => (this.rowData = data));
  }

  // Handle row selection changed event
  onSelectionChanged = (event: SelectionChangedEvent) => {
    console.log("Row Selected!");
  };

  // Handle cell editing event
  onCellValueChanged = (event: CellValueChangedEvent) => {
    console.log(`New Cell Value: ${event.value}`);
  };
}
```

[Live example: Testing Example](https://www.ag-grid.com/examples/deep-dive/testing-example/angular)

## Summary

Congratulations! You've completed the tutorial and built your first grid. By now, you should be familiar with the key concepts of AG Grid:

- **Row Data:** Your data, in JSON format, that you want the grid to display.
- **Column Definitions:** Define your columns and control column-specific functionality, like sorting and filtering.
- **Default Column Definitions:** Similar to Column Definitions, but applies configurations to all columns.
- **Grid Options:** Configure functionality which extends across the entire grid.
- **Grid Events:** Events raised by the grid, typically as a result of user interaction.
- **Value Formatters:** Functions used for basic text formatting
- **Cell Renderers:** Add your own components to cells

## Next Steps

Browse our guides to dive into specific features of the grid:

- [Theming & Styling](https://www.ag-grid.com/angular-data-grid/theming/)
- [Testing](https://www.ag-grid.com/angular-data-grid/testing/)
- [Security](https://www.ag-grid.com/angular-data-grid/security/)
