매출 상위 N명만 보기Show only the top N by sales
'상위 N행' 전용 연산자는 없지만, N번째 값을 구해서 '그 값 이상'으로 걸면 같은 효과를 내요. 정렬을 함께 걸어 순위대로 보여 줘요.There is no top-N operator; find the Nth value and filter for at least that value. Sort alongside to show the ranking.
코드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">
<select aria-label="보기" id="top">
<option value="all" selected>전체</option>
<option value="3">상위 3명</option>
<option value="5">상위 5명</option>
<option value="10">상위 10명</option>
</select>
</div>
<div id="grid" style="height: 700px"></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('top').addEventListener('change', (event) => actions.top(api, event.target.value));const reps = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'김서윤',
'장하은',
'윤재민',
];
const regions = ['서울', '부산', '대구', '광주'];
// 매출은 모두 다른 값이라 '상위 N명'이 정확히 N행이에요.
export const options = {
columns: [
{ id: 'rep', title: '담당자', width: 120 },
{ id: 'region', title: '지역', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
rep: reps[i % 10],
region: regions[(i * 3) % 4],
sales: 1200 + ((i * 7919) % 6400) + i,
})),
rowKey: 'id',
};
// 상위 N행 필터는 따로 연산자가 없어요. 전체 값을 큰 순으로 놓고 N번째 값을 구한 뒤,
// 그 값 '이상'(gte)만 보이게 하면 돼요. 값이 같은 행이 있으면 N행보다 많아질 수 있어요.
function topN(api, n) {
const values = options.rows.map((row) => row.sales).sort((a, b) => b - a);
const cutoff = values[Math.min(n, values.length) - 1];
api.setFilterModel({
match: 'all',
items: [{ columnId: 'sales', operator: 'gte', value: cutoff }],
});
api.setSortModel([{ columnId: 'sales', direction: 'desc' }]);
}
export function setup(api, log) {
const off = api.on('filterChanged', () => log({
ko: `보이는 행 ${api.getVisibleRowCount()} / 전체 ${api.getRowCount()}`,
en: `Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`,
}));
return () => off();
}
export const actions = {
top: (api, value) => {
if (!value || value === 'all') {
api.setFilterModel(null);
api.setSortModel([]);
return;
}
topN(api, Number(value));
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>매출 상위 N명만 보기</title>
</head>
<body>
<div class="toolbar">
<select aria-label="보기" id="top">
<option value="all" selected>전체</option>
<option value="3">상위 3명</option>
<option value="5">상위 5명</option>
<option value="10">상위 10명</option>
</select>
</div>
<div id="grid" style="height: 700px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const reps = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'김서윤',
'장하은',
'윤재민',
];
const regions = ['서울', '부산', '대구', '광주'];
// 매출은 모두 다른 값이라 '상위 N명'이 정확히 N행이에요.
const options = {
columns: [
{ id: 'rep', title: '담당자', width: 120 },
{ id: 'region', title: '지역', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
rep: reps[i % 10],
region: regions[(i * 3) % 4],
sales: 1200 + ((i * 7919) % 6400) + i,
})),
rowKey: 'id',
};
// 상위 N행 필터는 따로 연산자가 없어요. 전체 값을 큰 순으로 놓고 N번째 값을 구한 뒤,
// 그 값 '이상'(gte)만 보이게 하면 돼요. 값이 같은 행이 있으면 N행보다 많아질 수 있어요.
function topN(api, n) {
const values = options.rows.map((row) => row.sales).sort((a, b) => b - a);
const cutoff = values[Math.min(n, values.length) - 1];
api.setFilterModel({
match: 'all',
items: [{ columnId: 'sales', operator: 'gte', value: cutoff }],
});
api.setSortModel([{ columnId: 'sales', direction: 'desc' }]);
}
function setup(api, log) {
const off = api.on('filterChanged', () => log({
ko: `보이는 행 ${api.getVisibleRowCount()} / 전체 ${api.getRowCount()}`,
en: `Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`,
}));
return () => off();
}
const actions = {
top: (api, value) => {
if (!value || value === 'all') {
api.setFilterModel(null);
api.setSortModel([]);
return;
}
topN(api, Number(value));
},
};
options.ariaLabel = "매출 상위 N명만 보기";
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('top').addEventListener('change', (event) => actions.top(api, event.target.value));
</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">
<select
aria-label="보기"
disabled={!api}
onChange={(event) => api && actions.top(api, event.target.value)}
>
<option value="all">전체</option>
<option value="3">상위 3명</option>
<option value="5">상위 5명</option>
<option value="10">상위 10명</option>
</select>
</div>
<Grid style={{ height: 700 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
rep: string;
region: string;
sales: number;
}
const reps = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'김서윤',
'장하은',
'윤재민',
];
const regions = ['서울', '부산', '대구', '광주'];
// 매출은 모두 다른 값이라 '상위 N명'이 정확히 N행이에요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'rep', title: '담당자', width: 120 },
{ id: 'region', title: '지역', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
rep: reps[i % 10] as string,
region: regions[(i * 3) % 4] as string,
sales: 1200 + ((i * 7919) % 6400) + i,
})),
rowKey: 'id',
};
// 상위 N행 필터는 따로 연산자가 없어요. 전체 값을 큰 순으로 놓고 N번째 값을 구한 뒤,
// 그 값 '이상'(gte)만 보이게 하면 돼요. 값이 같은 행이 있으면 N행보다 많아질 수 있어요.
function topN(api: GridApi<Row>, n: number): void {
const values = options.rows!.map((row) => row.sales).sort((a, b) => b - a);
const cutoff = values[Math.min(n, values.length) - 1];
api.setFilterModel({
match: 'all',
items: [{ columnId: 'sales', operator: 'gte', value: cutoff }],
});
api.setSortModel([{ columnId: 'sales', direction: 'desc' }]);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const off = api.on('filterChanged', () =>
log({
ko: `보이는 행 ${api.getVisibleRowCount()} / 전체 ${api.getRowCount()}`,
en: `Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`,
}),
);
return () => off();
}
export const actions = {
top: (api: GridApi<Row>, value?: string) => {
if (!value || value === 'all') {
api.setFilterModel(null);
api.setSortModel([]);
return;
}
topN(api, Number(value));
},
};버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="보기"
:disabled="!api"
@change="api && actions.top(api, ($event.target as HTMLSelectElement).value)"
>
<option value="all" selected>전체</option>
<option value="3">상위 3명</option>
<option value="5">상위 5명</option>
<option value="10">상위 10명</option>
</select>
</div>
<Grid style="height: 700px" :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;
rep: string;
region: string;
sales: number;
}
const reps = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'김서윤',
'장하은',
'윤재민',
];
const regions = ['서울', '부산', '대구', '광주'];
// 매출은 모두 다른 값이라 '상위 N명'이 정확히 N행이에요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'rep', title: '담당자', width: 120 },
{ id: 'region', title: '지역', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
rep: reps[i % 10] as string,
region: regions[(i * 3) % 4] as string,
sales: 1200 + ((i * 7919) % 6400) + i,
})),
rowKey: 'id',
};
// 상위 N행 필터는 따로 연산자가 없어요. 전체 값을 큰 순으로 놓고 N번째 값을 구한 뒤,
// 그 값 '이상'(gte)만 보이게 하면 돼요. 값이 같은 행이 있으면 N행보다 많아질 수 있어요.
function topN(api: GridApi<Row>, n: number): void {
const values = options.rows!.map((row) => row.sales).sort((a, b) => b - a);
const cutoff = values[Math.min(n, values.length) - 1];
api.setFilterModel({
match: 'all',
items: [{ columnId: 'sales', operator: 'gte', value: cutoff }],
});
api.setSortModel([{ columnId: 'sales', direction: 'desc' }]);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const off = api.on('filterChanged', () =>
log({
ko: `보이는 행 ${api.getVisibleRowCount()} / 전체 ${api.getRowCount()}`,
en: `Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`,
}),
);
return () => off();
}
export const actions = {
top: (api: GridApi<Row>, value?: string) => {
if (!value || value === 'all') {
api.setFilterModel(null);
api.setSortModel([]);
return;
}
topN(api, Number(value));
},
};버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="보기"
[disabled]="!api"
(change)="api && actions.top(api, $any($event.target).value)"
>
<option value="all" selected>전체</option>
<option value="3">상위 3명</option>
<option value="5">상위 5명</option>
<option value="10">상위 10명</option>
</select>
</div>
<mx-grid style="height: 700px" [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;
rep: string;
region: string;
sales: number;
}
const reps = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'김서윤',
'장하은',
'윤재민',
];
const regions = ['서울', '부산', '대구', '광주'];
// 매출은 모두 다른 값이라 '상위 N명'이 정확히 N행이에요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'rep', title: '담당자', width: 120 },
{ id: 'region', title: '지역', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
rep: reps[i % 10] as string,
region: regions[(i * 3) % 4] as string,
sales: 1200 + ((i * 7919) % 6400) + i,
})),
rowKey: 'id',
};
// 상위 N행 필터는 따로 연산자가 없어요. 전체 값을 큰 순으로 놓고 N번째 값을 구한 뒤,
// 그 값 '이상'(gte)만 보이게 하면 돼요. 값이 같은 행이 있으면 N행보다 많아질 수 있어요.
function topN(api: GridApi<Row>, n: number): void {
const values = options.rows!.map((row) => row.sales).sort((a, b) => b - a);
const cutoff = values[Math.min(n, values.length) - 1];
api.setFilterModel({
match: 'all',
items: [{ columnId: 'sales', operator: 'gte', value: cutoff }],
});
api.setSortModel([{ columnId: 'sales', direction: 'desc' }]);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const off = api.on('filterChanged', () =>
log({
ko: `보이는 행 ${api.getVisibleRowCount()} / 전체 ${api.getRowCount()}`,
en: `Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`,
}),
);
return () => off();
}
export const actions = {
top: (api: GridApi<Row>, value?: string) => {
if (!value || value === 'all') {
api.setFilterModel(null);
api.setSortModel([]);
return;
}
topN(api, Number(value));
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<select aria-label="View" id="top">
<option value="all" selected>All</option>
<option value="3">Top 3</option>
<option value="5">Top 5</option>
<option value="10">Top 10</option>
</select>
</div>
<div id="grid" style="height: 700px"></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('top').addEventListener('change', (event) => actions.top(api, event.target.value));const reps = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
'Lucas Hayes',
'Mia Foster',
];
const regions = ['New York', 'Boston', 'Austin', 'Seattle'];
// Sales are all distinct, so "top N" is exactly N rows.
export const options = {
columns: [
{ id: 'rep', title: 'Rep', width: 140 },
{ id: 'region', title: 'Region', width: 110 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
],
rows: Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
rep: reps[i % 10],
region: regions[(i * 3) % 4],
sales: 12000 + ((i * 79190) % 64000) + i * 10,
})),
rowKey: 'id',
};
// There is no separate operator for a top-N filter. Sort all values from largest, take the N-th value,
// and show only rows at least that value (gte). Ties can make the result larger than N rows.
function topN(api, n) {
const values = options.rows.map((row) => row.sales).sort((a, b) => b - a);
const cutoff = values[Math.min(n, values.length) - 1];
api.setFilterModel({
match: 'all',
items: [{ columnId: 'sales', operator: 'gte', value: cutoff }],
});
api.setSortModel([{ columnId: 'sales', direction: 'desc' }]);
}
export function setup(api, log) {
const off = api.on('filterChanged', () => log(`Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`));
return () => off();
}
export const actions = {
top: (api, value) => {
if (!value || value === 'all') {
api.setFilterModel(null);
api.setSortModel([]);
return;
}
topN(api, Number(value));
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Show only the top N by sales</title>
</head>
<body>
<div class="toolbar">
<select aria-label="View" id="top">
<option value="all" selected>All</option>
<option value="3">Top 3</option>
<option value="5">Top 5</option>
<option value="10">Top 10</option>
</select>
</div>
<div id="grid" style="height: 700px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const reps = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
'Lucas Hayes',
'Mia Foster',
];
const regions = ['New York', 'Boston', 'Austin', 'Seattle'];
// Sales are all distinct, so "top N" is exactly N rows.
const options = {
columns: [
{ id: 'rep', title: 'Rep', width: 140 },
{ id: 'region', title: 'Region', width: 110 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
],
rows: Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
rep: reps[i % 10],
region: regions[(i * 3) % 4],
sales: 12000 + ((i * 79190) % 64000) + i * 10,
})),
rowKey: 'id',
};
// There is no separate operator for a top-N filter. Sort all values from largest, take the N-th value,
// and show only rows at least that value (gte). Ties can make the result larger than N rows.
function topN(api, n) {
const values = options.rows.map((row) => row.sales).sort((a, b) => b - a);
const cutoff = values[Math.min(n, values.length) - 1];
api.setFilterModel({
match: 'all',
items: [{ columnId: 'sales', operator: 'gte', value: cutoff }],
});
api.setSortModel([{ columnId: 'sales', direction: 'desc' }]);
}
function setup(api, log) {
const off = api.on('filterChanged', () => log(`Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`));
return () => off();
}
const actions = {
top: (api, value) => {
if (!value || value === 'all') {
api.setFilterModel(null);
api.setSortModel([]);
return;
}
topN(api, Number(value));
},
};
options.ariaLabel = "Show only the top N by sales";
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('top').addEventListener('change', (event) => actions.top(api, event.target.value));
</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">
<select
aria-label="View"
disabled={!api}
onChange={(event) => api && actions.top(api, event.target.value)}
>
<option value="all">All</option>
<option value="3">Top 3</option>
<option value="5">Top 5</option>
<option value="10">Top 10</option>
</select>
</div>
<Grid style={{ height: 700 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
rep: string;
region: string;
sales: number;
}
const reps = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
'Lucas Hayes',
'Mia Foster',
];
const regions = ['New York', 'Boston', 'Austin', 'Seattle'];
// Sales are all distinct, so "top N" is exactly N rows.
export const options: GridOptions<Row> = {
columns: [
{ id: 'rep', title: 'Rep', width: 140 },
{ id: 'region', title: 'Region', width: 110 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
],
rows: Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
rep: reps[i % 10] as string,
region: regions[(i * 3) % 4] as string,
sales: 12000 + ((i * 79190) % 64000) + i * 10,
})),
rowKey: 'id',
};
// There is no separate operator for a top-N filter. Sort all values from largest, take the N-th value,
// and show only rows at least that value (gte). Ties can make the result larger than N rows.
function topN(api: GridApi<Row>, n: number): void {
const values = options.rows!.map((row) => row.sales).sort((a, b) => b - a);
const cutoff = values[Math.min(n, values.length) - 1];
api.setFilterModel({
match: 'all',
items: [{ columnId: 'sales', operator: 'gte', value: cutoff }],
});
api.setSortModel([{ columnId: 'sales', direction: 'desc' }]);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const off = api.on('filterChanged', () =>
log(`Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`),
);
return () => off();
}
export const actions = {
top: (api: GridApi<Row>, value?: string) => {
if (!value || value === 'all') {
api.setFilterModel(null);
api.setSortModel([]);
return;
}
topN(api, Number(value));
},
};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">
<select
aria-label="View"
:disabled="!api"
@change="api && actions.top(api, ($event.target as HTMLSelectElement).value)"
>
<option value="all" selected>All</option>
<option value="3">Top 3</option>
<option value="5">Top 5</option>
<option value="10">Top 10</option>
</select>
</div>
<Grid style="height: 700px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
rep: string;
region: string;
sales: number;
}
const reps = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
'Lucas Hayes',
'Mia Foster',
];
const regions = ['New York', 'Boston', 'Austin', 'Seattle'];
// Sales are all distinct, so "top N" is exactly N rows.
export const options: GridOptions<Row> = {
columns: [
{ id: 'rep', title: 'Rep', width: 140 },
{ id: 'region', title: 'Region', width: 110 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
],
rows: Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
rep: reps[i % 10] as string,
region: regions[(i * 3) % 4] as string,
sales: 12000 + ((i * 79190) % 64000) + i * 10,
})),
rowKey: 'id',
};
// There is no separate operator for a top-N filter. Sort all values from largest, take the N-th value,
// and show only rows at least that value (gte). Ties can make the result larger than N rows.
function topN(api: GridApi<Row>, n: number): void {
const values = options.rows!.map((row) => row.sales).sort((a, b) => b - a);
const cutoff = values[Math.min(n, values.length) - 1];
api.setFilterModel({
match: 'all',
items: [{ columnId: 'sales', operator: 'gte', value: cutoff }],
});
api.setSortModel([{ columnId: 'sales', direction: 'desc' }]);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const off = api.on('filterChanged', () =>
log(`Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`),
);
return () => off();
}
export const actions = {
top: (api: GridApi<Row>, value?: string) => {
if (!value || value === 'all') {
api.setFilterModel(null);
api.setSortModel([]);
return;
}
topN(api, Number(value));
},
};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">
<select
aria-label="View"
[disabled]="!api"
(change)="api && actions.top(api, $any($event.target).value)"
>
<option value="all" selected>All</option>
<option value="3">Top 3</option>
<option value="5">Top 5</option>
<option value="10">Top 10</option>
</select>
</div>
<mx-grid style="height: 700px" [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;
rep: string;
region: string;
sales: number;
}
const reps = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
'Lucas Hayes',
'Mia Foster',
];
const regions = ['New York', 'Boston', 'Austin', 'Seattle'];
// Sales are all distinct, so "top N" is exactly N rows.
export const options: GridOptions<Row> = {
columns: [
{ id: 'rep', title: 'Rep', width: 140 },
{ id: 'region', title: 'Region', width: 110 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
],
rows: Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
rep: reps[i % 10] as string,
region: regions[(i * 3) % 4] as string,
sales: 12000 + ((i * 79190) % 64000) + i * 10,
})),
rowKey: 'id',
};
// There is no separate operator for a top-N filter. Sort all values from largest, take the N-th value,
// and show only rows at least that value (gte). Ties can make the result larger than N rows.
function topN(api: GridApi<Row>, n: number): void {
const values = options.rows!.map((row) => row.sales).sort((a, b) => b - a);
const cutoff = values[Math.min(n, values.length) - 1];
api.setFilterModel({
match: 'all',
items: [{ columnId: 'sales', operator: 'gte', value: cutoff }],
});
api.setSortModel([{ columnId: 'sales', direction: 'desc' }]);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const off = api.on('filterChanged', () =>
log(`Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`),
);
return () => off();
}
export const actions = {
top: (api: GridApi<Row>, value?: string) => {
if (!value || value === 'all') {
api.setFilterModel(null);
api.setSortModel([]);
return;
}
topN(api, Number(value));
},
};