Skip to content

Use with Angular ​

<mx-grid> is a standalone component. It creates the grid, passes new options to the core, emits events through one output, and cleans up when the component goes away. Sorting, selection, editing and saving live in the core, so the other guides apply unchanged. This guide covers only what differs in Angular. For React and Vue side by side, see the framework guide.

Angular 17 or later is required. All code here uses @Input and @Output, so it works in apps that do not use signals.

Install and show a grid ​

bash
pnpm add @maxgrid/angular @maxgrid/themes
ts
// At the top of main.ts, or add the same file to "styles" in angular.json.
import '@maxgrid/themes/grid.css';

Give <mx-grid> its own height. A height on an outer element alone lets the grid grow and render every row.

ts
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { GridComponent, type GridOptions } from '@maxgrid/angular';

interface Employee {
  id: number;
  name: string;
  department: string;
  salary: number;
}

@Component({
  selector: 'app-employees',
  standalone: true,
  imports: [GridComponent],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: ` <mx-grid style="height: 320px" [options]="options" /> `,
})
export class EmployeesComponent {
  readonly options: GridOptions<Employee> = {
    columns: [
      { id: 'name', title: 'Name', width: 140 },
      { id: 'department', title: 'Department', width: 120 },
      { id: 'salary', title: 'Salary', kind: 'number', width: 120, align: 'end' },
    ],
    rows: [
      { id: 1, name: 'Liam Carter', department: 'Engineering', salary: 5200 },
      { id: 2, name: 'Emma Wilson', department: 'Design', salary: 4800 },
    ],
    rowKey: 'id',
  };
}

Inputs and the output ​

NameKindDescription
options@Input (required)GridOptions<TRow>. setOptions runs only when the reference changes
events@InputEvent names to emit. Without it, every event is emitted
gridEvent@OutputOne output that carries { name, payload }. It enters the zone only when observed

You can pass a signal's value: [options]="opts()". Changing an object in place keeps the same reference and does nothing, so pass a new object.

ts
replaceRows(rows: Employee[]) {
  this.options = { ...this.options, rows };
}

Why there is one output ​

One output per event, such as (sortChanged) and (selectionChanged), would shorten templates. But Angular's AOT compiler reads @Output statically, so outputs generated from a list of event names cannot ship in a library. A hand-written set would also drift from the core as events are added. So the output is (gridEvent), and you branch on the name.

isGridEvent narrows the payload to the type for that name.

ts
import { GridComponent, isGridEvent, type GridEventMessage } from '@maxgrid/angular';

onEvent(event: GridEventMessage<Employee>) {
  if (isGridEvent(event, 'selectionChanged')) {
    this.selectedKeys = event.payload.selectedKeys; // RowKey[]
  } else if (isGridEvent(event, 'sortChanged')) {
    this.sortModel = event.payload.sortModel;
  }
}
html
<mx-grid [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />

List only the names the screen uses in [events], for example relayed = ['selectionChanged', 'sortChanged'] as const. The list is read once when the grid is created, so keep it constant.

Get the GridApi ​

There are two ways.

  • The ready event carries api once the grid exists. Add 'ready' to [events].
  • viewChild and getApi() work from the parent's ngAfterViewInit. It returns null during server rendering or before the grid exists.
ts
import { AfterViewInit, Component, viewChild } from '@angular/core';
import { GridComponent, type GridApi } from '@maxgrid/angular';

export class EmployeesComponent implements AfterViewInit {
  private readonly grid = viewChild.required<GridComponent<Employee>>(GridComponent);
  api: GridApi<Employee> | null = null;

  ngAfterViewInit() {
    this.api = this.grid().getApi();
  }

  addRow() {
    this.api?.addRows([{ id: 99, name: 'Jack Moore', department: 'Sales', salary: 4000 }], 0);
  }
}

Always check for null. getApi() also returns null again after the component is destroyed.

OnPush, signals and zones ​

The grid is an OnPush component with an empty template, so it works under an OnPush parent. Three things matter for change detection.

  • Creating the grid, setOptions, scrolling, mouse and keyboard input all run in NgZone.runOutsideAngular. Scrolling or moving the mouse does not trigger change detection.
  • An event enters the zone through NgZone.run only if (gridEvent) has a subscriber and the name is in [events]. Without [events], scrolled enters on every scroll, so drop it from the list if you do not need the scroll position.
  • Setting a signal in the handler redraws an OnPush template. This also holds in zoneless apps.
ts
readonly selection = signal<RowKey[]>([]);
readonly total = computed(() =>
  this.selection().reduce((sum, key) => sum + (this.salaryOf(key) ?? 0), 0),
);

onEvent(event: GridEventMessage<Employee>) {
  if (isGridEvent(event, 'selectionChanged')) this.selection.set(event.payload.selectedKeys);
}

createSaveState() collects the save state (pending count, saving, last failure) into a signal.

ts
import { createSaveState } from '@maxgrid/angular';

readonly saves = createSaveState();
// Template: (gridEvent)="saves.handle($event)"  /  {{ saves.state().count }} pending, failed: {{ saves.state().lastError }}

saves.state() returns { count, added, modified, removed, saving, lastError }. [events] must include changesCountChanged, saveStarted and saveFailed.

Services and HttpClient ​

Fetch in a service and let the screen component pass the result to the grid. Turn on the loading option while the request runs. Requests can overlap, so use switchMap to keep only the latest answer.

ts
import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subject, catchError, of, switchMap, tap } from 'rxjs';

export class EmployeesComponent {
  private readonly http = inject(HttpClient);
  private readonly reload$ = new Subject<void>();
  options: GridOptions<Employee> = { columns, rows: [], rowKey: 'id', loading: true };

  constructor() {
    this.reload$
      .pipe(
        tap(() => (this.options = { ...this.options, loading: true })),
        switchMap(() =>
          this.http.get<Employee[]>('/api/employees').pipe(catchError(() => of(null))),
        ),
        takeUntilDestroyed(),
      )
      .subscribe((rows) => {
        // A failure arrives as null. Keep the current rows and only end the loading state.
        this.options = { ...this.options, ...(rows ? { rows } : {}), loading: false };
      });
    this.reload$.next();
  }
}

catchError sits inside switchMap on purpose. Outside, the stream ends on the first failure and a retry button does nothing. Show the failure message in the screen, and let the retry button call reload$.next().

For screens where a stream keeps changing rows, such as stock levels or prices, pass only the changed rows to api.updateRows and end the subscription with takeUntilDestroyed().

Use with Reactive Forms ​

Let the form hold its own values and apply them to the grid only when valid. When the selection changes, fill the form with patchValue.

ts
form = inject(NonNullableFormBuilder).group({
  name: ['', Validators.required],
  salary: [0, [Validators.required, Validators.min(0)]],
});

onEvent(event: GridEventMessage<Employee>) {
  if (!isGridEvent(event, 'selectionChanged')) return;
  const row = this.api?.getRowByKey(event.payload.selectedKeys[0] ?? -1);
  if (row) this.form.patchValue(row);
  else this.form.reset();
}

apply() {
  const key = this.api?.getSelectedKeys()[0];
  const row = key === undefined ? undefined : this.api?.getRowByKey(key);
  if (!row || this.form.invalid) return;
  this.api?.updateRows([{ ...row, ...this.form.getRawValue() }]);
}

Cells edited inside the grid are validated by the column's validation. Use form validators only for inputs outside the grid. If both validate the same value, the rules drift apart.

Sync with router query params ​

Keeping filter and sort in the URL gives the same screen after a reload and with Back. Make sure the grid-to-URL path and the URL-to-grid path do not trigger each other.

ts
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private applying = false;

onEvent(event: GridEventMessage<Employee>) {
  if (this.applying) return;
  if (isGridEvent(event, 'filterChanged')) {
    const dept = event.payload.filterModel?.items[0]?.value;
    this.router.navigate([], {
      relativeTo: this.route,
      queryParams: { dept: typeof dept === 'string' ? dept : null },
      queryParamsHandling: 'merge',
    });
  }
}

constructor() {
  this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe((params) => {
    const dept = params.get('dept');
    this.applying = true;
    this.api?.setFilterModel(
      dept ? { match: 'all', items: [{ columnId: 'department', operator: 'equals', value: dept }] } : null,
    );
    this.applying = false;
  });
}

Users can edit a query string. Accept only values this screen can produce, and turn those into a filter model.

Draw cells with components ​

angularCell and angularEditor turn Angular components into cell renderers and editors. How to write the component and the editor rules are in Cells from components. The Angular-specific behavior:

WhatHow it works
CreationcreateComponent inside the cell element, attached to ApplicationRef, outside the zone
Updating valuesVirtual scrolling reuses slots, so setInput and detectChanges change only the inputs on each row
Component outputsReceive them with outputs: { picked: (v) => ... }. Handlers run inside NgZone.run
ServicesThe cell uses the environment injector of <mx-grid>, so providedIn: 'root' services work
CleanupWhen a slot goes away or the grid is destroyed: detachView, destroy, then the element is removed
Exceptions in a cellOnly that cell shows an error. The grid keeps working

A column built with angularCell cannot be used in a grid created outside <mx-grid>. There is no injector there, and the error says so.

Server-side rendering ​

The grid is not created on the server. ngOnInit creates it only when PLATFORM_ID is the browser, so the server emits an empty <mx-grid>. The template is empty, so there is no hydration mismatch. Even if the data exists during SSR, the grid first draws in the browser. If the list itself must be indexable, render the same data as plain HTML separately.

getApi() returns null on the server. In code that can run there, such as the constructor and ngOnInit, use api?..

Generic types ​

GridComponent<TRow> is generic. If [options] is GridOptions<Employee>, $event follows as GridEventMessage<Employee>. When you grab a reference with viewChild, pass the type argument yourself.

ts
private readonly grid = viewChild.required<GridComponent<Employee>>(GridComponent);

TRow must be an object type. Import GridApi, ColumnDef, GridOptions and the event payload types from @maxgrid/angular, with no separate @maxgrid/core install.

Common mistakes ​

  • Mutating options in place. this.options.rows.push(...) keeps the reference, so nothing changes. Build a new object or use api.addRows.
  • Changing [events] later. The list is read once when the grid is created. Changing it while running leaves the subscriptions as they were.
  • Calling getApi() in ngOnInit. The child does not exist yet in the parent's ngOnInit. Use the ready event or ngAfterViewInit.
  • Expecting a parent's providers in a cell component. Only the environment injector is visible. Pass component-level values through inputs.
  • Sending new rows while there are unsaved changes. A new array clears the change log. Check api.hasChanges() before reloading server data.
  • Calling a service on every scrolled event. Each scroll triggers change detection and a request. Add debounceTime where you need it, or do not receive the event at all.

Examples ​

These examples show JavaScript, React, Vue and Angular code from one source. Add the Angular-only parts, such as services and forms, by following the code above.

GoalExample
Collect sort, selection and focus as stateng-state-store
Loading, failure and retryng-http-lifecycle
Update rows from a streamng-stream-updates
Validate a form draft, then applyng-form-panel
Report a button click in a cellng-cell-output
Dropdown editorng-select-editor
Visible count and selected totalng-derived-totals
Query string and Backng-query-history
Only the events you need with 100,000 rowsng-event-budget
Save barng-save-bar
Follow the system themeng-system-theme