Angular UI Components Documentation
Cloud Firestore, the database of Firebase, keeps documents in collections and tells a listening app about every change. This tutorial shows the two ways to put a collection in an Angular jqxGrid: a live grid that holds the latest orders and changes with the database, and a grid that reads a large collection a page at a time with query cursors. Edits are written back to the documents, and the database's security rules decide what is accepted.

You need a Firebase project with Cloud Firestore (console.firebase.google.com), or the Firestore emulator on your computer: npx firebase-tools emulators:start --only firestore --project demo-jqwidgets (it needs Java 21). The examples use the emulator and a collection orders with fields customer, product, quantity, price, orderDate (a timestamp) and status. Use an Angular CLI app set up as in Angular CLI with jQWidgets, and install the Firebase SDK:
npm install firebase
The examples call the SDK's functions directly. AngularFire, the Angular library for Firebase, wraps the same functions in injectable services; the grid's side is the same with either.
Your app's configuration is under Project settings > General > Your apps in the console; with the emulator, a project id starting with demo- is enough. The app and the database are made once, when src/app/app.ts loads:
import { initializeApp } from 'firebase/app';
import {
collection, connectFirestoreEmulator, doc, getFirestore, limit, onSnapshot, orderBy, query,
QueryDocumentSnapshot, Timestamp, updateDoc
} from 'firebase/firestore';
import { jqxGridComponent, jqxGridModule } from 'jqwidgets-ng/jqxgrid';
// Your web app's configuration: Project settings > General > Your apps in the Firebase
// console. (A project id that starts with "demo-" works with the emulator only.)
const firebaseConfig = {
projectId: 'demo-jqwidgets'
// apiKey, authDomain, appId ... for a real project
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
// The local emulator (firebase emulators:start); leave this line out for your project.
connectFirestoreEmulator(db, '127.0.0.1', 8080);
In a larger app, make them in a file of their own (or with AngularFire's provideFirebaseApp and provideFirestore in app.config.ts), so that every component uses the same database.
The grid is bound to a local array, so it sorts, filters and pages in the browser. toRow turns a document into a row: its id, its fields, and the Firestore Timestamp as a JavaScript Date, which the date column formats and filters.
// A document as a grid row: its id, its fields, and the Timestamp as a Date
const toRow = (snapshot: QueryDocumentSnapshot) => {
const data = snapshot.data() as OrderDocument;
return { ...data, id: snapshot.id, orderDate: data.orderDate.toDate() };
};
The source uses the document id as the row id (id: 'id'), which is what lets each change find its row. Its settings are a field of their own, so that the first snapshot can put the documents in localdata:
export class App {
// …
private readonly settings = {
datatype: 'array',
localdata: [] as ReturnType<typeof toRow>[],
id: 'id',
datafields: [
{ name: 'id', type: 'string' },
{ name: 'customer', type: 'string' },
{ name: 'product', type: 'string' },
{ name: 'quantity', type: 'number' },
{ name: 'price', type: 'number' },
{ name: 'orderDate', type: 'date' },
{ name: 'status', type: 'string' }
]
};
readonly source = new jqx.dataAdapter(this.settings);
// …
}
onSnapshot listens to a query: the latest 500 orders. Its first answer fills the grid; each later one carries only the documents that were added, changed or removed, and the grid applies them by document id with addrow, updaterow and deleterow. When a new order arrives, the oldest of the 500 leaves the query and its row goes.
export class App {
// …
constructor() {
const destroyRef = inject(DestroyRef);
// Once the grid exists: the latest 500 orders, live. The first snapshot fills the
// grid, each later one brings only what changed. Edits, by this page or anyone else,
// arrive the same way. The listener stops with the component.
afterNextRender(() => {
let loaded = false;
const latest = query(collection(db, 'orders'), orderBy('orderDate', 'desc'), limit(500));
const unsubscribe = onSnapshot(latest, (snapshot) => {
const grid = this.grid();
if (!loaded) {
this.settings.localdata = snapshot.docs.map(toRow);
grid.updatebounddata();
loaded = true;
return;
}
this.applying = true;
for (const change of snapshot.docChanges()) {
if (change.type === 'added') grid.addrow(change.doc.id, toRow(change.doc), 'first');
if (change.type === 'modified') grid.updaterow(change.doc.id, toRow(change.doc));
if (change.type === 'removed') grid.deleterow(change.doc.id);
}
this.applying = false;
}, (error) => {
this.status.set(`Could not load the orders: ${error.message}`);
});
destroyRef.onDestroy(unsubscribe);
});
}
// …
}
The rows reach the grid through its methods, never through its inputs: the [source] input stays the same adapter, so a change does not bind the grid again and the user keeps the sort, filters and page (see Sorting, filtering and paging on inputs that change). The listener starts in afterNextRender, once the grid exists, and onSnapshot returns the function that stops it, which DestroyRef.onDestroy calls when the component is destroyed.
<h1>Orders</h1>
<p role="status">{{ status() }}</p>
<jqxGrid #grid
[theme]="'fluent'"
[width]="'100%'"
[height]="560"
[source]="source"
[columns]="columns"
[pageable]="true"
[pagesize]="20"
[sortable]="true"
[filterable]="true"
[showfilterrow]="true"
[editable]="true"
[selectionmode]="'singlecell'"
(onCellvaluechanged)="cellValueChanged($event)">
</jqxGrid>
A changed cell is written to its document with updateDoc. Firestore shows the new value at once, before the server answers. If the security rules refuse the write, Firestore takes it back, and the snapshot listener of step 2 puts the old value into the cell; the page only reports why, through the status signal.
export class App {
// …
// An edit is written to its document. Firestore shows it at once, and takes it back if
// the security rules refuse it (the snapshot listener above brings the old value).
cellValueChanged(event: CellValueChangedEvent): void {
if (!this.applying) {
this.saveEdit(event.args);
}
}
private async saveEdit({ datafield, rowindex, newvalue }: CellValueChangedEvent['args']): Promise<void> {
const row = this.grid().getrowdata(rowindex);
try {
await updateDoc(doc(db, 'orders', row.id), { [datafield]: newvalue });
this.status.set('Saved.');
} catch (error) {
this.status.set(`Not saved: ${(error as Error).message}`);
}
}
}
The rules are the real protection, since anyone can change an app's JavaScript in the browser. These allow reading orders and changing only their quantity (a whole number above 0) and status (one of four values):
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Anyone may read orders and change their quantity and status (the tutorial's grid);
// a real app checks request.auth here.
match /orders/{orderId} {
allow read: if true;
allow update: if request.resource.data.diff(resource.data).affectedKeys().hasOnly(['quantity', 'status'])
&& request.resource.data.quantity is int && request.resource.data.quantity > 0
&& request.resource.data.status in ['New', 'Shipped', 'Delivered', 'Cancelled'];
allow create: if request.resource.data.keys().hasAll(['customer', 'product', 'quantity', 'price', 'orderDate', 'status'])
&& request.resource.data.orderDate is timestamp;
allow delete: if true;
}
}
}
Deploy them with firebase deploy --only firestore:rules; the emulator reads them from firestore.rules next to firebase.json. A quantity of 2.5 entered through the grid's API is refused by the rules, and the cell shows the old quantity again.
A live query that holds the whole collection is right for hundreds or a few thousand documents. For more, read one page at a time. Firestore has no offsets: a page starts after a document, the last one of the page before it. The grid runs in virtual mode with loadServerData, and the component keeps the last document of each page it has read, so the next page is one query and a jump ahead reads the pages in between once.
export class App {
// …
// Firestore pages with cursors, not offsets: a page starts after the last document of
// the page before it. lastDocs[n] is the last document of page n, for the current sort
// and page size; going to a page further on reads the pages in between once. The
// count is an aggregation query: it is billed as one read per 1,000 documents.
private lastDocs: QueryDocumentSnapshot[] = [];
private order = '';
private total = 0;
private async loadPage(params: GridState): Promise<OrdersPage> {
const field = params.sortdatafield && sortable.has(params.sortdatafield) && params.sortorder ? params.sortdatafield : 'orderDate';
const direction = params.sortorder === 'asc' ? 'asc' : 'desc';
if (this.order !== `${field} ${direction} ${params.pagesize}`) {
this.order = `${field} ${direction} ${params.pagesize}`;
this.lastDocs = [];
this.total = (await getCountFromServer(orders)).data().count;
}
const sorted = query(orders, orderBy(field, direction));
let n = Math.min(this.lastDocs.length, params.pagenum);
let page: QuerySnapshot;
do {
const after = n > 0 ? [startAfter(this.lastDocs[n - 1])] : [];
page = await getDocs(query(sorted, ...after, limit(params.pagesize)));
if (page.docs.length) this.lastDocs[n] = page.docs[page.docs.length - 1];
} while (++n <= params.pagenum);
return { records: page.docs.map(toRow), totalrecords: this.total };
}
// …
}
The source and adapter are those of the server-side tutorials. Sorting is done by Firestore, so a new sort starts a new list of cursors:
export class App {
// …
private createSource() {
const settings = {
// (json: the adapter asks for data through loadServerData, which an array source never does)
datatype: 'json',
id: 'id',
datafields: [
{ name: 'id', type: 'string' },
{ name: 'customer', type: 'string' },
{ name: 'product', type: 'string' },
{ name: 'quantity', type: 'number' },
{ name: 'price', type: 'number' },
{ name: 'orderDate', type: 'date' },
{ name: 'status', type: 'string' }
],
// The adapter needs a url to ask for data; loadServerData below does the asking.
url: 'orders',
totalrecords: 0,
// Sorting happens in Firestore: ask again.
sort: () => this.grid().updatebounddata('sort')
};
const adapter = new jqx.dataAdapter(settings, {
loadServerData: (params: GridState, _settings: unknown, callback: (page: OrdersPage) => void) => {
this.loadPage(params).then((page) => {
this.status.set('');
adapter.totalrecords = page.totalrecords;
callback(page);
}, (error: Error) => {
this.status.set(`Could not load the orders: ${error.message}`);
callback({ records: [], totalrecords: 0 });
});
}
});
return adapter;
}
}
<h1>Orders</h1>
<p role="status">{{ status() }}</p>
<jqxGrid #grid
[theme]="'fluent'"
[width]="'100%'"
[height]="560"
[source]="source"
[columns]="columns"
[virtualmode]="true"
[rendergridrows]="rendergridrows"
[pageable]="true"
[pagesize]="20"
[sortable]="true">
</jqxGrid>
Firestore sorts by one field here without extra setup. Sorting by one field and filtering by another needs a composite index: Firestore's error message has a link that creates it. getCountFromServer counts without reading the documents; it is read again only when the sort or page size changes. As in the other server-side examples, loadServerData is a plain function that sets adapter.totalrecords itself, for versions before 27.1.0.
The live grid, src/app/app.ts:
import { afterNextRender, Component, DestroyRef, inject, signal, viewChild } from '@angular/core';
import { initializeApp } from 'firebase/app';
import {
collection,
connectFirestoreEmulator,
doc,
getFirestore,
limit,
onSnapshot,
orderBy,
query,
QueryDocumentSnapshot,
Timestamp,
updateDoc
} from 'firebase/firestore';
import { jqxGridComponent, jqxGridModule } from 'jqwidgets-ng/jqxgrid';
// Your web app's configuration: Project settings > General > Your apps in the Firebase
// console. (A project id that starts with "demo-" works with the emulator only.)
const firebaseConfig = {
projectId: 'demo-jqwidgets'
// apiKey, authDomain, appId ... for a real project
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
// The local emulator (firebase emulators:start); leave this line out for your project.
connectFirestoreEmulator(db, '127.0.0.1', 8080);
// An order as Firestore keeps it
interface OrderDocument {
customer: string;
product: string;
quantity: number;
price: number;
orderDate: Timestamp;
status: string;
}
// A grid event carries its details in event.args.
interface CellValueChangedEvent {
args: { rowindex: number; datafield: string; oldvalue: unknown; newvalue: unknown };
}
const statuses = ['New', 'Shipped', 'Delivered', 'Cancelled'];
// A document as a grid row: its id, its fields, and the Timestamp as a Date
const toRow = (snapshot: QueryDocumentSnapshot) => {
const data = snapshot.data() as OrderDocument;
return { ...data, id: snapshot.id, orderDate: data.orderDate.toDate() };
};
@Component({ selector: 'app-root', imports: [jqxGridModule], templateUrl: './app.html' })
export class App {
readonly grid = viewChild.required<jqxGridComponent>('grid');
// What the page tells the user: why something failed, or that an edit was saved.
readonly status = signal('');
private readonly settings = {
datatype: 'array',
localdata: [] as ReturnType<typeof toRow>[],
id: 'id',
datafields: [
{ name: 'id', type: 'string' },
{ name: 'customer', type: 'string' },
{ name: 'product', type: 'string' },
{ name: 'quantity', type: 'number' },
{ name: 'price', type: 'number' },
{ name: 'orderDate', type: 'date' },
{ name: 'status', type: 'string' }
]
};
readonly source = new jqx.dataAdapter(this.settings);
readonly columns: jqwidgets.GridColumn[] = [
{ text: 'Customer', datafield: 'customer', width: 180, editable: false },
{ text: 'Product', datafield: 'product', width: 120, editable: false },
{
text: 'Quantity',
datafield: 'quantity',
width: 90,
cellsalign: 'right',
align: 'right',
filtertype: 'number',
columntype: 'numberinput',
createeditor: (_row, _value, editor) =>
editor.jqxNumberInput({ decimalDigits: 0, min: 1, spinButtons: true }),
validation: (_cell, value) =>
(value !== undefined && Number.isInteger(value) && value > 0) || {
result: false,
message: 'A whole number above 0'
}
},
{
text: 'Price',
datafield: 'price',
width: 90,
cellsalign: 'right',
align: 'right',
cellsformat: 'c2',
filtertype: 'number',
editable: false
},
{
text: 'Date',
datafield: 'orderDate',
width: 110,
cellsformat: 'yyyy-MM-dd',
filtertype: 'range',
editable: false
},
{
text: 'Status',
datafield: 'status',
filtertype: 'list',
filteritems: statuses,
columntype: 'dropdownlist',
createeditor: (_row, _value, editor) =>
editor.jqxDropDownList({ source: statuses, autoDropDownHeight: true })
}
];
// Set while the snapshot listener changes the grid's rows, which are not edits to save.
private applying = false;
constructor() {
const destroyRef = inject(DestroyRef);
// Once the grid exists: the latest 500 orders, live. The first snapshot fills the
// grid, each later one brings only what changed. Edits, by this page or anyone else,
// arrive the same way. The listener stops with the component.
afterNextRender(() => {
let loaded = false;
const latest = query(
collection(db, 'orders'),
orderBy('orderDate', 'desc'),
limit(500)
);
const unsubscribe = onSnapshot(
latest,
(snapshot: any) => {
const grid = this.grid();
if (!loaded) {
this.settings.localdata = snapshot.docs.map(toRow);
grid.updatebounddata();
loaded = true;
return;
}
this.applying = true;
for (const change of snapshot.docChanges()) {
if (change.type === 'added')
grid.addrow(change.doc.id, toRow(change.doc), 'first');
if (change.type === 'modified')
grid.updaterow(change.doc.id, toRow(change.doc));
if (change.type === 'removed') grid.deleterow(change.doc.id);
}
this.applying = false;
},
(error: any) => {
this.status.set(`Could not load the orders: ${error.message}`);
}
);
destroyRef.onDestroy(unsubscribe);
});
}
// An edit is written to its document. Firestore shows it at once, and takes it back if
// the security rules refuse it (the snapshot listener above brings the old value).
cellValueChanged(event: CellValueChangedEvent): void {
if (!this.applying) {
this.saveEdit(event.args);
}
}
private async saveEdit({
datafield,
rowindex,
newvalue
}: CellValueChangedEvent['args']): Promise<void> {
const row = this.grid().getrowdata(rowindex);
try {
await updateDoc(doc(db, 'orders', row.id), { [datafield]: newvalue });
this.status.set('Saved.');
} catch (error) {
this.status.set(`Not saved: ${(error as Error).message}`);
}
}
}
src/app/app.html:
<h1>Orders</h1>
<p role="status">{{ status() }}</p>
<jqxGrid #grid
[theme]="'fluent'"
[width]="'100%'"
[height]="560"
[source]="source"
[columns]="columns"
[pageable]="true"
[pagesize]="20"
[sortable]="true"
[filterable]="true"
[showfilterrow]="true"
[editable]="true"
[selectionmode]="'singlecell'"
(onCellvaluechanged)="cellValueChanged($event)">
</jqxGrid>
The paged grid, src/app/app.ts:
import { Component, signal, viewChild } from '@angular/core';
import { initializeApp } from 'firebase/app';
import {
collection,
connectFirestoreEmulator,
getCountFromServer,
getDocs,
getFirestore,
limit,
orderBy,
query,
QueryDocumentSnapshot,
QuerySnapshot,
startAfter,
Timestamp
} from 'firebase/firestore';
import { jqxGridComponent, jqxGridModule } from 'jqwidgets-ng/jqxgrid';
const app = initializeApp({ projectId: 'demo-jqwidgets' });
const db = getFirestore(app);
connectFirestoreEmulator(db, '127.0.0.1', 8080);
const orders = collection(db, 'orders');
const sortable = new Set(['customer', 'product', 'quantity', 'price', 'orderDate']);
// The grid's state, as loadServerData receives it
interface GridState {
pagenum: number;
pagesize: number;
sortdatafield?: string;
sortorder?: string;
}
interface OrdersPage {
records: object[];
totalrecords: number;
}
// A document as a grid row: its id, its fields, and the Timestamp as a Date
const toRow = (snapshot: QueryDocumentSnapshot) => {
const data = snapshot.data() as { orderDate: Timestamp };
return { ...data, id: snapshot.id, orderDate: data.orderDate.toDate() };
};
@Component({ selector: 'app-root', imports: [jqxGridModule], templateUrl: './app.html' })
export class App {
readonly grid = viewChild.required<jqxGridComponent>('grid');
readonly status = signal('');
readonly source = this.createSource();
readonly columns: jqwidgets.GridColumn[] = [
{ text: 'Customer', datafield: 'customer', width: 180 },
{ text: 'Product', datafield: 'product', width: 120 },
{ text: 'Quantity', datafield: 'quantity', width: 90, cellsalign: 'right', align: 'right' },
{
text: 'Price',
datafield: 'price',
width: 90,
cellsalign: 'right',
align: 'right',
cellsformat: 'c2'
},
{ text: 'Date', datafield: 'orderDate', width: 110, cellsformat: 'yyyy-MM-dd' },
{ text: 'Status', datafield: 'status', sortable: false }
];
readonly rendergridrows = (params: { data: unknown[] }) => params.data;
// Firestore pages with cursors, not offsets: a page starts after the last document of
// the page before it. lastDocs[n] is the last document of page n, for the current sort
// and page size; going to a page further on reads the pages in between once. The
// count is an aggregation query: it is billed as one read per 1,000 documents.
private lastDocs: QueryDocumentSnapshot[] = [];
private order = '';
private total = 0;
private async loadPage(params: GridState): Promise<OrdersPage> {
const field =
params.sortdatafield && sortable.has(params.sortdatafield) && params.sortorder
? params.sortdatafield
: 'orderDate';
const direction = params.sortorder === 'asc' ? 'asc' : 'desc';
if (this.order !== `${field} ${direction} ${params.pagesize}`) {
this.order = `${field} ${direction} ${params.pagesize}`;
this.lastDocs = [];
this.total = (await getCountFromServer(orders)).data().count;
}
const sorted = query(orders, orderBy(field, direction));
let n = Math.min(this.lastDocs.length, params.pagenum);
let page: QuerySnapshot;
do {
const after = n > 0 ? [startAfter(this.lastDocs[n - 1])] : [];
page = await getDocs(query(sorted, ...after, limit(params.pagesize)));
if (page.docs.length) this.lastDocs[n] = page.docs[page.docs.length - 1];
} while (++n <= params.pagenum);
return { records: page.docs.map(toRow), totalrecords: this.total };
}
private createSource() {
const settings = {
// (json: the adapter asks for data through loadServerData, which an array source never does)
datatype: 'json',
id: 'id',
datafields: [
{ name: 'id', type: 'string' },
{ name: 'customer', type: 'string' },
{ name: 'product', type: 'string' },
{ name: 'quantity', type: 'number' },
{ name: 'price', type: 'number' },
{ name: 'orderDate', type: 'date' },
{ name: 'status', type: 'string' }
],
// The adapter needs a url to ask for data; loadServerData below does the asking.
url: 'orders',
totalrecords: 0,
// Sorting happens in Firestore: ask again.
sort: () => this.grid().updatebounddata('sort')
};
const adapter = new jqx.dataAdapter(settings, {
loadServerData: (
params: GridState,
_settings: unknown,
callback: (page: OrdersPage) => void
) => {
this.loadPage(params).then(
(page) => {
this.status.set('');
adapter.totalrecords = page.totalrecords;
callback(page);
},
(error: Error) => {
this.status.set(`Could not load the orders: ${error.message}`);
callback({ records: [], totalrecords: 0 });
}
);
}
});
return adapter;
}
}
src/app/app.html:
<h1>Orders</h1>
<p role="status">{{ status() }}</p>
<jqxGrid #grid
[theme]="'fluent'"
[width]="'100%'"
[height]="560"
[source]="source"
[columns]="columns"
[virtualmode]="true"
[rendergridrows]="rendergridrows"
[pageable]="true"
[pagesize]="20"
[sortable]="true">
</jqxGrid>
Start the emulator and add some orders (the emulator's UI, or a short script with addDoc), then run ng serve with the live grid. Change a document in the Firebase console or the emulator UI: its row changes in the grid. Add an order dated today: it appears at the top. With the paged grid, go to page 3, then click the Quantity header: Firestore sorts and the grid shows page 3 of the new order.