본문으로 건너뛰기

Angular에서 쓰기 ​

<mx-grid>는 standalone 컴포넌트예요. 그리드를 만들고, 옵션이 바뀌면 core에 넘기고, 이벤트를 하나의 출력으로 내보내고, 컴포넌트가 사라질 때 정리하는 일만 해요. 정렬·선택·편집·저장은 core가 하므로 해당 가이드의 설명이 그대로 맞아요. 여기서는 Angular에서만 달라지는 부분을 다뤄요. React와 Vue까지 나란히 보려면 프레임워크별 사용법을 봐요.

Angular 17 이상이 필요해요. 이 가이드의 코드는 모두 @Input과 @Output 방식이라 Signals를 쓰지 않는 앱에서도 같아요.

설치와 첫 화면 ​

bash
pnpm add @maxgrid/angular @maxgrid/themes
ts
// main.ts 맨 위, 또는 angular.json의 styles에 같은 파일을 추가해요.
import '@maxgrid/themes/grid.css';

<mx-grid>에 높이를 직접 줘요. 바깥 요소에만 주면 그리드가 늘어나 모든 행이 그려져요.

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: '이름', width: 140 },
      { id: 'department', title: '부서', width: 120 },
      { id: 'salary', title: '급여', kind: 'number', width: 120, align: 'end' },
    ],
    rows: [
      { id: 1, name: '김민준', department: '개발', salary: 5200000 },
      { id: 2, name: '이서연', department: '디자인', salary: 4800000 },
    ],
    rowKey: 'id',
  };
}

입력과 출력 ​

이름종류설명
options@Input (필수)GridOptions<TRow>. 참조가 바뀔 때만 core의 setOptions가 불려요
events@Input내보낼 이벤트 이름 목록. 생략하면 모든 이벤트를 내보내요
gridEvent@Output{ name, payload } 한 종류. 구독자가 있을 때만 Zone으로 들어와요

options에는 signal 값도 쓸 수 있어요. [options]="opts()"처럼 읽어서 넘기면 돼요. 객체 안을 직접 고치면 참조가 같아서 아무 일도 안 일어나니까, 새 객체로 바꿔서 넘겨요.

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

출력이 하나인 이유 ​

이벤트마다 (sortChanged), (selectionChanged) 같은 출력을 따로 두면 템플릿은 짧아져요. 하지만 Angular의 AOT 컴파일은 @Output을 정적으로만 읽어서, 이벤트 이름 목록으로 출력을 만들어 내는 방식은 라이브러리로 배포할 수 없어요. 이벤트를 늘릴 때마다 래퍼가 core와 어긋날 위험도 있어요. 그래서 출력은 (gridEvent) 하나이고, 이름으로 갈라 써요.

isGridEvent가 이름에 맞는 페이로드 타입으로 좁혀 줘요.

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)" />

[events]에는 화면이 쓰는 이름만 적어요. 이 화면이라면 relayed = ['selectionChanged', 'sortChanged'] as const예요. 이 목록은 처음 만들 때 한 번 읽으니까 나중에 바꾸지 않는 상수로 둬요.

GridApi 얻기 ​

API는 두 가지로 얻어요.

  • ready 이벤트: 그리드가 만들어진 뒤 페이로드에 api가 들어 있어요. [events]에 'ready'를 넣어요.
  • viewChild와 getApi(): 부모의 ngAfterViewInit부터 쓸 수 있어요. 서버 렌더링 중이거나 아직 만들어지지 않았다면 null이에요.
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: '박지훈', department: '영업', salary: 4000000 }], 0);
  }
}

항상 null 검사를 해요. getApi()가 돌려주는 값은 컴포넌트가 파괴되면 null로 돌아가요.

OnPush·Signals·Zone ​

그리드는 OnPush 컴포넌트이고 템플릿이 비어 있어서, 부모가 OnPush여도 그대로 동작해요. 변경 감지와 관련해 알아 둘 것은 세 가지예요.

  • 그리드 생성, setOptions, 스크롤, 마우스, 키보드는 NgZone.runOutsideAngular 안에서 일어나요. 스크롤하거나 마우스를 움직여도 변경 감지가 돌지 않아요.
  • 이벤트는 (gridEvent) 구독자가 있고 [events]에 든 것만 NgZone.run으로 들어와요. [events]를 생략하면 scrolled도 매번 들어오니까, 스크롤 위치가 필요 없으면 목록에서 빼요.
  • 이벤트 핸들러에서 signal을 갱신하면 OnPush 템플릿이 다시 그려져요. Zoneless 앱에서도 같아요.
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()가 signal로 모아 줘요.

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

readonly saves = createSaveState();
// 템플릿: (gridEvent)="saves.handle($event)"  /  {{ saves.state().count }}건 변경, 실패: {{ saves.state().lastError }}

saves.state()는 { count, added, modified, removed, saving, lastError }를 돌려줘요. [events]에 changesCountChanged, saveStarted, saveFailed가 들어 있어야 해요.

서비스와 HttpClient ​

데이터는 서비스에서 받고, 화면 컴포넌트가 그리드에 넘겨요. 요청 중에는 loading 옵션을 켜요. 같은 화면에서 요청이 겹칠 수 있으니 가장 최근 응답만 쓰도록 switchMap을 써요.

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) => {
        // 실패하면 null이 와요. 기존 행을 두고 로딩만 끝내요.
        this.options = { ...this.options, ...(rows ? { rows } : {}), loading: false };
      });
    this.reload$.next();
  }
}

catchError를 switchMap 안쪽에 두는 이유가 있어요. 바깥에 두면 첫 실패에서 스트림이 끝나서 다시 시도 버튼이 아무 일도 하지 않아요. 실패 메시지는 화면이 따로 보여 주고, 다시 시도 버튼이 reload$.next()를 불러요.

RxJS 스트림이 행을 계속 바꾸는 화면(재고, 시세)에서는 api.updateRows로 바뀐 행만 넘겨요. 구독은 takeUntilDestroyed()로 끊어요.

Reactive Forms와 함께 쓰기 ​

폼은 자기 값을 따로 들고 있다가, 검증을 통과했을 때만 그리드에 반영해요. 선택이 바뀌면 폼에 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() }]);
}

그리드 안에서 직접 고치는 셀은 컬럼의 validation이 검증하고, 폼의 검증은 폼 밖 입력에만 써요. 두 곳이 같은 값을 검증하면 규칙이 갈라져요.

라우터 쿼리와 맞추기 ​

필터·정렬을 URL에 두면 새로고침과 뒤로 가기에서 같은 화면이 나와요. 그리드에서 URL로 보낼 때와 URL에서 그리드로 돌려놓을 때가 서로를 부르지 않게 해요.

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;
  });
}

쿼리 문자열은 사용자가 고칠 수 있어요. 화면이 만들어 내는 값만 받아서 필터 모델로 바꿔요.

컴포넌트로 셀 그리기 ​

angularCell과 angularEditor가 Angular 컴포넌트를 셀 렌더러와 에디터로 바꿔 줘요. 컴포넌트 작성법과 에디터 규칙은 컴포넌트로 셀 그리기에 있어요. Angular에서 알아 둘 동작만 정리하면 이래요.

일어떻게 되는지
만들기createComponent로 셀 요소 안에 만들고 ApplicationRef에 붙여요. Zone 밖에서 일어나요
값 갱신가상 스크롤이 칸을 재사용하므로 행이 바뀔 때마다 setInput과 detectChanges로 입력만 바꿔요
컴포넌트 출력outputs: { picked: (v) => ... }로 받아요. 핸들러는 NgZone.run 안에서 불려요
서비스 주입<mx-grid>의 환경 주입기를 써서 providedIn: 'root' 서비스는 inject()로 쓸 수 있어요
정리칸이 없어질 때와 그리드를 파괴할 때 detachView, destroy, 요소 제거를 순서대로 해요
컴포넌트가 던진 예외그 셀만 오류 표시가 되고 그리드는 계속 동작해요

컬럼 정의를 컴포넌트 밖의 상수로 두고 angularCell을 쓰면, 그 컬럼은 <mx-grid>가 아닌 곳에서 만든 그리드에 쓸 수 없어요. 주입기가 없어서 명확한 오류가 나요.

서버 렌더링(SSR) ​

서버에서는 그리드를 만들지 않아요. PLATFORM_ID가 브라우저일 때만 ngOnInit이 그리드를 만들기 때문에, 서버가 내보내는 HTML은 빈 <mx-grid>예요. 템플릿이 비어 있어서 hydration 불일치도 생기지 않아요. 데이터가 SSR 때 이미 있어도 그리드는 브라우저에서 처음 그려지니까, 목록 자체가 검색 엔진에 필요하면 같은 데이터를 일반 HTML로 따로 내보내요.

getApi()는 서버에서 null이에요. 서버에서 돌 수 있는 코드(생성자, ngOnInit)에서는 api?. 로 접근해요.

제네릭 타입 ​

GridComponent<TRow>는 제네릭이에요. 템플릿의 [options]가 GridOptions<Employee>이면 $event도 GridEventMessage<Employee>로 이어져요. viewChild로 참조를 잡을 때는 타입 인자를 직접 줘요.

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

TRow는 객체 타입이어야 해요. GridApi, ColumnDef, GridOptions, 이벤트 페이로드 타입은 @maxgrid/core를 따로 설치하지 않고 @maxgrid/angular에서 바로 가져와요.

흔한 실수 ​

  • 옵션을 제자리에서 고쳐요. this.options.rows.push(...)는 참조가 같아서 반영되지 않아요. 새 객체를 만들거나 api.addRows를 써요.
  • [events]를 나중에 바꿔요. 목록은 그리드를 만들 때 한 번만 읽어요. 실행 중에 바꿔도 구독은 그대로예요.
  • ngOnInit에서 getApi()를 불러요. 부모의 ngOnInit에는 자식이 아직 없어요. ready 이벤트나 ngAfterViewInit을 써요.
  • 셀 컴포넌트가 부모의 providers를 기대해요. 환경 주입기만 보이므로, 부모 컴포넌트 단위의 제공자는 inputs로 값을 넘겨요.
  • 저장하지 않은 변경이 있는데 새 rows를 내려보내요. 새 배열을 통째로 넘기면 변경 내역이 비워져요. 서버 데이터를 다시 받기 전에 api.hasChanges()를 확인해요.
  • scrolled를 구독한 채 서비스를 호출해요. 스크롤마다 변경 감지와 요청이 일어나요. 필요한 곳에서 debounceTime을 걸거나 이벤트를 아예 받지 않아요.

예제 ​

이 예제들은 같은 소스에서 JavaScript·React·Vue·Angular 코드를 보여 줘요. 서비스나 폼 같은 Angular 전용 부분은 앞의 코드를 따라 붙이면 돼요.

하려는 일예제
정렬·선택·포커스를 상태로 모으기ng-state-store
로딩·실패·재시도ng-http-lifecycle
스트림으로 행 갱신ng-stream-updates
폼 초안 검증 후 반영ng-form-panel
셀 안 버튼 클릭 알리기ng-cell-output
드롭다운 에디터ng-select-editor
보이는 행 수·선택 합계ng-derived-totals
쿼리 문자열과 뒤로 가기ng-query-history
10만 행에서 필요한 이벤트만ng-event-budget
저장 바ng-save-bar
시스템 테마 따르기ng-system-theme