저장하지 않았으면 떠나기 전에 경고하기Warn before leaving with unsaved changes
저장하지 않은 수정이 있을 때만, 탭을 닫거나 새로고침하려 하면 브라우저가 한 번 더 물어봐요. 수정이 없으면 그냥 떠나요. 화면이 사라질 때는 이 경고도 함께 걷어 내야 해요.Only when there are unsaved edits does the browser ask once more before the tab is closed or reloaded. With no edits you leave silently. The warning must be removed when the screen goes away.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="markSaved">저장한 것으로 처리</button>
<button type="button" id="discard">되돌리기</button>
</div>
<div id="grid" style="height: 290px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('markSaved').addEventListener('click', () => actions.markSaved(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));const items = ['A4 용지', '볼펜 세트', '포스트잇', '스테이플러', '노트'];
export const options = {
columns: [
{ id: 'item', title: '품목', width: 180, editable: true },
{
id: 'quantity',
title: '수량',
kind: 'number',
width: 110,
editable: true,
validation: { min: 0 },
},
],
rows: items.map((item, i) => ({ id: i + 1, item, quantity: 10 + i * 5 })),
rowKey: 'id',
};
// '떠날 때 묻기'는 그리드 밖의 window에 걸어요. 이 화면이 사라질 때 꼭 풀어 주지 않으면 화면이 없어진 뒤에도
// 계속 남아요. 저장하지 않은 변경이 있으면 브라우저가 떠나기 전에 한 번 물어요.
export function setup(api, log) {
const warn = (event) => {
if (api.hasChanges())
event.preventDefault();
};
window.addEventListener('beforeunload', warn);
log({
ko: '표의 값을 고쳐 보세요. 저장하지 않은 변경이 있으면 창을 닫을 때 브라우저가 물어요',
en: 'Edit a value in the table. With unsaved changes, the browser asks when you close the window',
});
const off = api.on('changesCountChanged', (e) => log({
ko: e.count > 0
? `저장하지 않은 변경 ${e.count}개 — 지금 떠나면 브라우저가 물어요`
: '저장하지 않은 변경이 없어요',
en: e.count > 0
? `${e.count} unsaved changes — the browser asks if you leave now`
: 'No unsaved changes',
}));
return () => {
window.removeEventListener('beforeunload', warn);
off();
};
}
export const actions = {
markSaved: (api) => api.commitChanges(),
discard: (api) => api.rollbackChanges(),
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>저장하지 않았으면 떠나기 전에 경고하기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="markSaved">저장한 것으로 처리</button>
<button type="button" id="discard">되돌리기</button>
</div>
<div id="grid" style="height: 290px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const items = ['A4 용지', '볼펜 세트', '포스트잇', '스테이플러', '노트'];
const options = {
columns: [
{ id: 'item', title: '품목', width: 180, editable: true },
{
id: 'quantity',
title: '수량',
kind: 'number',
width: 110,
editable: true,
validation: { min: 0 },
},
],
rows: items.map((item, i) => ({ id: i + 1, item, quantity: 10 + i * 5 })),
rowKey: 'id',
};
// '떠날 때 묻기'는 그리드 밖의 window에 걸어요. 이 화면이 사라질 때 꼭 풀어 주지 않으면 화면이 없어진 뒤에도
// 계속 남아요. 저장하지 않은 변경이 있으면 브라우저가 떠나기 전에 한 번 물어요.
function setup(api, log) {
const warn = (event) => {
if (api.hasChanges())
event.preventDefault();
};
window.addEventListener('beforeunload', warn);
log({
ko: '표의 값을 고쳐 보세요. 저장하지 않은 변경이 있으면 창을 닫을 때 브라우저가 물어요',
en: 'Edit a value in the table. With unsaved changes, the browser asks when you close the window',
});
const off = api.on('changesCountChanged', (e) => log({
ko: e.count > 0
? `저장하지 않은 변경 ${e.count}개 — 지금 떠나면 브라우저가 물어요`
: '저장하지 않은 변경이 없어요',
en: e.count > 0
? `${e.count} unsaved changes — the browser asks if you leave now`
: 'No unsaved changes',
}));
return () => {
window.removeEventListener('beforeunload', warn);
off();
};
}
const actions = {
markSaved: (api) => api.commitChanges(),
discard: (api) => api.rollbackChanges(),
};
options.ariaLabel = "저장하지 않았으면 떠나기 전에 경고하기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('markSaved').addEventListener('click', () => actions.markSaved(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.markSaved(api)}
>저장한 것으로 처리</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.discard(api)}
>되돌리기</button>
</div>
<Grid style={{ height: 290 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
item: string;
quantity: number;
}
const items = ['A4 용지', '볼펜 세트', '포스트잇', '스테이플러', '노트'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: '품목', width: 180, editable: true },
{
id: 'quantity',
title: '수량',
kind: 'number',
width: 110,
editable: true,
validation: { min: 0 },
},
],
rows: items.map((item, i) => ({ id: i + 1, item, quantity: 10 + i * 5 })),
rowKey: 'id',
};
// '떠날 때 묻기'는 그리드 밖의 window에 걸어요. 이 화면이 사라질 때 꼭 풀어 주지 않으면 화면이 없어진 뒤에도
// 계속 남아요. 저장하지 않은 변경이 있으면 브라우저가 떠나기 전에 한 번 물어요.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const warn = (event: BeforeUnloadEvent): void => {
if (api.hasChanges()) event.preventDefault();
};
window.addEventListener('beforeunload', warn);
log({
ko: '표의 값을 고쳐 보세요. 저장하지 않은 변경이 있으면 창을 닫을 때 브라우저가 물어요',
en: 'Edit a value in the table. With unsaved changes, the browser asks when you close the window',
});
const off = api.on('changesCountChanged', (e) =>
log({
ko:
e.count > 0
? `저장하지 않은 변경 ${e.count}개 — 지금 떠나면 브라우저가 물어요`
: '저장하지 않은 변경이 없어요',
en:
e.count > 0
? `${e.count} unsaved changes — the browser asks if you leave now`
: 'No unsaved changes',
}),
);
return () => {
window.removeEventListener('beforeunload', warn);
off();
};
}
export const actions = {
markSaved: (api: GridApi<Row>) => api.commitChanges(),
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.markSaved(api)"
>저장한 것으로 처리</button>
<button type="button" :disabled="!api" @click="api && actions.discard(api)">되돌리기</button>
</div>
<Grid style="height: 290px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
item: string;
quantity: number;
}
const items = ['A4 용지', '볼펜 세트', '포스트잇', '스테이플러', '노트'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: '품목', width: 180, editable: true },
{
id: 'quantity',
title: '수량',
kind: 'number',
width: 110,
editable: true,
validation: { min: 0 },
},
],
rows: items.map((item, i) => ({ id: i + 1, item, quantity: 10 + i * 5 })),
rowKey: 'id',
};
// '떠날 때 묻기'는 그리드 밖의 window에 걸어요. 이 화면이 사라질 때 꼭 풀어 주지 않으면 화면이 없어진 뒤에도
// 계속 남아요. 저장하지 않은 변경이 있으면 브라우저가 떠나기 전에 한 번 물어요.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const warn = (event: BeforeUnloadEvent): void => {
if (api.hasChanges()) event.preventDefault();
};
window.addEventListener('beforeunload', warn);
log({
ko: '표의 값을 고쳐 보세요. 저장하지 않은 변경이 있으면 창을 닫을 때 브라우저가 물어요',
en: 'Edit a value in the table. With unsaved changes, the browser asks when you close the window',
});
const off = api.on('changesCountChanged', (e) =>
log({
ko:
e.count > 0
? `저장하지 않은 변경 ${e.count}개 — 지금 떠나면 브라우저가 물어요`
: '저장하지 않은 변경이 없어요',
en:
e.count > 0
? `${e.count} unsaved changes — the browser asks if you leave now`
: 'No unsaved changes',
}),
);
return () => {
window.removeEventListener('beforeunload', warn);
off();
};
}
export const actions = {
markSaved: (api: GridApi<Row>) => api.commitChanges(),
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.markSaved(api)"
>저장한 것으로 처리</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.discard(api)"
>되돌리기</button>
</div>
<mx-grid style="height: 290px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
item: string;
quantity: number;
}
const items = ['A4 용지', '볼펜 세트', '포스트잇', '스테이플러', '노트'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: '품목', width: 180, editable: true },
{
id: 'quantity',
title: '수량',
kind: 'number',
width: 110,
editable: true,
validation: { min: 0 },
},
],
rows: items.map((item, i) => ({ id: i + 1, item, quantity: 10 + i * 5 })),
rowKey: 'id',
};
// '떠날 때 묻기'는 그리드 밖의 window에 걸어요. 이 화면이 사라질 때 꼭 풀어 주지 않으면 화면이 없어진 뒤에도
// 계속 남아요. 저장하지 않은 변경이 있으면 브라우저가 떠나기 전에 한 번 물어요.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const warn = (event: BeforeUnloadEvent): void => {
if (api.hasChanges()) event.preventDefault();
};
window.addEventListener('beforeunload', warn);
log({
ko: '표의 값을 고쳐 보세요. 저장하지 않은 변경이 있으면 창을 닫을 때 브라우저가 물어요',
en: 'Edit a value in the table. With unsaved changes, the browser asks when you close the window',
});
const off = api.on('changesCountChanged', (e) =>
log({
ko:
e.count > 0
? `저장하지 않은 변경 ${e.count}개 — 지금 떠나면 브라우저가 물어요`
: '저장하지 않은 변경이 없어요',
en:
e.count > 0
? `${e.count} unsaved changes — the browser asks if you leave now`
: 'No unsaved changes',
}),
);
return () => {
window.removeEventListener('beforeunload', warn);
off();
};
}
export const actions = {
markSaved: (api: GridApi<Row>) => api.commitChanges(),
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="markSaved">Mark as saved</button>
<button type="button" id="discard">Discard</button>
</div>
<div id="grid" style="height: 290px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('markSaved').addEventListener('click', () => actions.markSaved(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));const items = ['A4 paper', 'Ballpoint pens', 'Sticky notes', 'Stapler', 'Notebook'];
export const options = {
columns: [
{ id: 'item', title: 'Item', width: 180, editable: true },
{
id: 'quantity',
title: 'Quantity',
kind: 'number',
width: 110,
editable: true,
validation: { min: 0 },
},
],
rows: items.map((item, i) => ({ id: i + 1, item, quantity: 10 + i * 5 })),
rowKey: 'id',
};
// 'Ask when leaving' is attached to the window outside the grid. If you do not remove it when this screen goes away, it
// stays even after the screen is gone. With unsaved changes, the browser asks once before leaving.
export function setup(api, log) {
const warn = (event) => {
if (api.hasChanges())
event.preventDefault();
};
window.addEventListener('beforeunload', warn);
log('Edit a value in the table. With unsaved changes, the browser asks when you close the window');
const off = api.on('changesCountChanged', (e) => log(e.count > 0
? `${e.count} unsaved changes — the browser asks if you leave now`
: 'No unsaved changes'));
return () => {
window.removeEventListener('beforeunload', warn);
off();
};
}
export const actions = {
markSaved: (api) => api.commitChanges(),
discard: (api) => api.rollbackChanges(),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Warn before leaving with unsaved changes</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="markSaved">Mark as saved</button>
<button type="button" id="discard">Discard</button>
</div>
<div id="grid" style="height: 290px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const items = ['A4 paper', 'Ballpoint pens', 'Sticky notes', 'Stapler', 'Notebook'];
const options = {
columns: [
{ id: 'item', title: 'Item', width: 180, editable: true },
{
id: 'quantity',
title: 'Quantity',
kind: 'number',
width: 110,
editable: true,
validation: { min: 0 },
},
],
rows: items.map((item, i) => ({ id: i + 1, item, quantity: 10 + i * 5 })),
rowKey: 'id',
};
// 'Ask when leaving' is attached to the window outside the grid. If you do not remove it when this screen goes away, it
// stays even after the screen is gone. With unsaved changes, the browser asks once before leaving.
function setup(api, log) {
const warn = (event) => {
if (api.hasChanges())
event.preventDefault();
};
window.addEventListener('beforeunload', warn);
log('Edit a value in the table. With unsaved changes, the browser asks when you close the window');
const off = api.on('changesCountChanged', (e) => log(e.count > 0
? `${e.count} unsaved changes — the browser asks if you leave now`
: 'No unsaved changes'));
return () => {
window.removeEventListener('beforeunload', warn);
off();
};
}
const actions = {
markSaved: (api) => api.commitChanges(),
discard: (api) => api.rollbackChanges(),
};
options.ariaLabel = "Warn before leaving with unsaved changes";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('markSaved').addEventListener('click', () => actions.markSaved(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.markSaved(api)}
>Mark as saved</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.discard(api)}
>Discard</button>
</div>
<Grid style={{ height: 290 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
item: string;
quantity: number;
}
const items = ['A4 paper', 'Ballpoint pens', 'Sticky notes', 'Stapler', 'Notebook'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: 'Item', width: 180, editable: true },
{
id: 'quantity',
title: 'Quantity',
kind: 'number',
width: 110,
editable: true,
validation: { min: 0 },
},
],
rows: items.map((item, i) => ({ id: i + 1, item, quantity: 10 + i * 5 })),
rowKey: 'id',
};
// 'Ask when leaving' is attached to the window outside the grid. If you do not remove it when this screen goes away, it
// stays even after the screen is gone. With unsaved changes, the browser asks once before leaving.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const warn = (event: BeforeUnloadEvent): void => {
if (api.hasChanges()) event.preventDefault();
};
window.addEventListener('beforeunload', warn);
log(
'Edit a value in the table. With unsaved changes, the browser asks when you close the window',
);
const off = api.on('changesCountChanged', (e) =>
log(
e.count > 0
? `${e.count} unsaved changes — the browser asks if you leave now`
: 'No unsaved changes',
),
);
return () => {
window.removeEventListener('beforeunload', warn);
off();
};
}
export const actions = {
markSaved: (api: GridApi<Row>) => api.commitChanges(),
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.markSaved(api)"
>Mark as saved</button>
<button type="button" :disabled="!api" @click="api && actions.discard(api)">Discard</button>
</div>
<Grid style="height: 290px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
item: string;
quantity: number;
}
const items = ['A4 paper', 'Ballpoint pens', 'Sticky notes', 'Stapler', 'Notebook'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: 'Item', width: 180, editable: true },
{
id: 'quantity',
title: 'Quantity',
kind: 'number',
width: 110,
editable: true,
validation: { min: 0 },
},
],
rows: items.map((item, i) => ({ id: i + 1, item, quantity: 10 + i * 5 })),
rowKey: 'id',
};
// 'Ask when leaving' is attached to the window outside the grid. If you do not remove it when this screen goes away, it
// stays even after the screen is gone. With unsaved changes, the browser asks once before leaving.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const warn = (event: BeforeUnloadEvent): void => {
if (api.hasChanges()) event.preventDefault();
};
window.addEventListener('beforeunload', warn);
log(
'Edit a value in the table. With unsaved changes, the browser asks when you close the window',
);
const off = api.on('changesCountChanged', (e) =>
log(
e.count > 0
? `${e.count} unsaved changes — the browser asks if you leave now`
: 'No unsaved changes',
),
);
return () => {
window.removeEventListener('beforeunload', warn);
off();
};
}
export const actions = {
markSaved: (api: GridApi<Row>) => api.commitChanges(),
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.markSaved(api)"
>Mark as saved</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.discard(api)"
>Discard</button>
</div>
<mx-grid style="height: 290px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
item: string;
quantity: number;
}
const items = ['A4 paper', 'Ballpoint pens', 'Sticky notes', 'Stapler', 'Notebook'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'item', title: 'Item', width: 180, editable: true },
{
id: 'quantity',
title: 'Quantity',
kind: 'number',
width: 110,
editable: true,
validation: { min: 0 },
},
],
rows: items.map((item, i) => ({ id: i + 1, item, quantity: 10 + i * 5 })),
rowKey: 'id',
};
// 'Ask when leaving' is attached to the window outside the grid. If you do not remove it when this screen goes away, it
// stays even after the screen is gone. With unsaved changes, the browser asks once before leaving.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const warn = (event: BeforeUnloadEvent): void => {
if (api.hasChanges()) event.preventDefault();
};
window.addEventListener('beforeunload', warn);
log(
'Edit a value in the table. With unsaved changes, the browser asks when you close the window',
);
const off = api.on('changesCountChanged', (e) =>
log(
e.count > 0
? `${e.count} unsaved changes — the browser asks if you leave now`
: 'No unsaved changes',
),
);
return () => {
window.removeEventListener('beforeunload', warn);
off();
};
}
export const actions = {
markSaved: (api: GridApi<Row>) => api.commitChanges(),
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};