Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

README.md

279 lines8.6 KB

1# @tanstack/angular-db
2​
3Angular hooks for TanStack DB. See [TanStack/db](https://github.com/TanStack/db) for more details.
4​
5Installation
6​
7 npm install @tanstack/angular-db @tanstack/db
8​
9Usage
10​
11Basic Setup
12​
13First, create a collection:
14​
15 import { createCollection, localOnlyCollectionOptions } from "@tanstack/db"
16​
17 interface Todo {
18 id: number
19 text: string
20 completed: boolean
21 projectID: number
22 created_at: Date
23 }
24​
25 export const todosCollection = createCollection(
26 localOnlyCollectionOptions<Todo>({
27 getKey: (todo: Todo) => todo.id,
28 initialData: [
29 {
30 id: 1,
31 text: "Learn Angular",
32 completed: false,
33 projectID: 1,
34 created_at: new Date(),
35 },
36 ],
37 })
38 )
39​
40Using injectLiveQuery in Components
41​
42Direct Collection Usage
43​
44The simplest way to use injectLiveQuery is to pass a collection directly:
45​
46 import { Component } from "@angular/core"
47 import { injectLiveQuery } from "@tanstack/angular-db"
48 import { todosCollection } from "./collections/todos-collection"
49​
50 @Component({
51 selector: "app-all-todos",
52 template: `
53 @if (allTodos.isReady()) {
54 <div>Total todos: {{ allTodos.data().length }}</div>
55 @for (todo of allTodos.data(); track todo.id) {
56 <div>{{ todo.text }}</div>
57 }
58 } @else {
59 <div>Loading todos...</div>
60 }
61 `,
62 })
63 export class AllTodosComponent {
64 // Direct collection usage - gets all items
65 allTodos = injectLiveQuery(todosCollection)
66 }
67​
68Static Query Functions
69​
70You can create filtered queries using a query function. Note: The query function is evaluated once and is not reactive to signal changes:
71​
72 import { Component } from "@angular/core"
73 import { injectLiveQuery } from "@tanstack/angular-db"
74 import { eq } from "@tanstack/db"
75 import { todosCollection } from "./collections/todos-collection"
76​
77 @Component({
78 selector: "app-todos",
79 template: `
80 @if (todoQuery.isReady()) {
81 @for (todo of todoQuery.data(); track todo.id) {
82 <div class="todo-item">
83 {{ todo.text }}
84 <button (click)="toggleTodo(todo.id)">
85 {{ todo.completed ? "Undo" : "Complete" }}
86 </button>
87 </div>
88 }
89 } @else {
90 <div>Loading todos...</div>
91 }
92 `,
93 })
94 export class TodosComponent {
95 // Static query - filters for incomplete todos
96 // This will not react to signal changes within the function
97 todoQuery = injectLiveQuery((q) =>
98 q
99 .from({ todo: todosCollection })
100 .where(({ todo }) => eq(todo.completed, false))
101 )
102​
103 toggleTodo(id: number) {
104 todosCollection.utils.begin()
105 todosCollection.utils.write({
106 type: 'update',
107 key: id,
108 value: { completed: true }
109 })
110 todosCollection.utils.commit()
111 }
112 }
113​
114Reactive Queries with Parameters
115​
116For queries that need to react to component state changes, use the reactive parameters overload:
117​
118 import { Component, signal } from "@angular/core"
119 import { injectLiveQuery } from "@tanstack/angular-db"
120 import { eq } from "@tanstack/db"
121 import { todosCollection } from "./collections/todos-collection"
122​
123 @Component({
124 selector: "app-project-todos",
125 template: `
126 <select (change)="selectedProjectId.set(+$any($event).target.value)">
127 <option [value]="1">Project 1</option>
128 <option [value]="2">Project 2</option>
129 <option [value]="3">Project 3</option>
130 </select>
131​
132 @if (todoQuery.isReady()) {
133 <div>Todos for project {{ selectedProjectId() }}:</div>
134 @for (todo of todoQuery.data(); track todo.id) {
135 <div class="todo-item">
136 {{ todo.text }}
137 </div>
138 }
139 } @else {
140 <div>Loading todos...</div>
141 }
142 `,
143 })
144 export class ProjectTodosComponent {
145 selectedProjectId = signal(1)
146​
147 // Reactive query - automatically recreates when selectedProjectId changes
148 todoQuery = injectLiveQuery({
149 params: () => ({ projectID: this.selectedProjectId() }),
150 query: ({ params, q }) =>
151 q
152 .from({ todo: todosCollection })
153 .where(({ todo }) => eq(todo.completed, false))
154 .where(({ todo }) => eq(todo.projectID, params.projectID)),
155 })
156 }
157​
158Advanced Configuration
159​
160You can also pass a full configuration object:
161​
162 import { Component } from "@angular/core"
163 import { injectLiveQuery } from "@tanstack/angular-db"
164 import { eq } from "@tanstack/db"
165 import { todosCollection } from "./collections/todos-collection"
166​
167 @Component({
168 selector: "app-configured-todos",
169 template: `
170 @if (todoQuery.isReady()) {
171 @for (todo of todoQuery.data(); track todo.id) {
172 <div>{{ todo.text }}</div>
173 }
174 }
175 `,
176 })
177 export class ConfiguredTodosComponent {
178 todoQuery = injectLiveQuery({
179 query: (q) =>
180 q
181 .from({ todo: todosCollection })
182 .where(({ todo }) => eq(todo.completed, false))
183 .select(({ todo }) => ({
184 id: todo.id,
185 text: todo.text,
186 })),
187 startSync: true,
188 gcTime: 5000,
189 })
190 }
191​
192Important Notes
193​
194Reactivity Behavior
195​
196- Direct collection: Automatically reactive to collection changes
197- Static query function: Query is built once and is not reactive to signals read within the function
198- Reactive parameters: Query rebuilds when any signal read in params() changes
199- Collection configuration: Static, not reactive to external signals
200​
201Lifecycle Management
202​
203- injectLiveQuery automatically handles subscription cleanup when the component is destroyed
204- Each call to injectLiveQuery creates a new collection instance (no caching/reuse)
205- Collections are started immediately and will sync according to their configuration
206​
207Template Usage
208​
209Use Angular's new control flow syntax for best performance:
210​
211 @if (query.isReady()) {
212 @for (item of query.data(); track item.id) {
213 <div>{{ item.text }}</div>
214 }
215 } @else if (query.isError()) {
216 <div>Error loading data</div>
217 } @else {
218 <div>Loading...</div>
219 }
220​
221API
222​
223injectLiveQuery()
224​
225Angular injection function for TanStack DB live queries. Must be called within an injection context (e.g., component constructor, inject(), or field initializer).
226​
227Overloads
228​
229 // Direct collection - reactive to collection changes
230 function injectLiveQuery<TResult, TKey, TUtils>(
231 collection: Collection<TResult, TKey, TUtils>
232 ): LiveQueryResult<TResult>
233​
234 // Static query function - NOT reactive to signals within function
235 function injectLiveQuery<TContext>(
236 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>
237 ): LiveQueryResult<TContext>
238​
239 // Reactive query with parameters - recreates when params() signals change
240 function injectLiveQuery<TContext, TParams>(options: {
241 params: () => TParams
242 query: (args: {
243 params: TParams
244 q: InitialQueryBuilder
245 }) => QueryBuilder<TContext>
246 }): LiveQueryResult<TContext>
247​
248 // Collection configuration - static configuration
249 function injectLiveQuery<TContext>(
250 config: LiveQueryCollectionConfig<TContext>
251 ): LiveQueryResult<TContext>
252​
253Returns
254​
255An object with Angular signals:
256​
257- data: Signal<Array<T>> - Array of query results, automatically updates
258- state: Signal<Map<Key, T>> - Map of results by key, automatically updates
259- collection: Signal<Collection> - The underlying collection instance
260- status: Signal<CollectionStatus> - Current status ('idle' | 'loading' | 'ready' | 'error' | 'cleaned-up')
261- isLoading: Signal<boolean> - true when status is 'loading'
262- isReady: Signal<boolean> - true when status is 'ready'
263- isIdle: Signal<boolean> - true when status is 'idle'
264- isError: Signal<boolean> - true when status is 'error'
265- isCleanedUp: Signal<boolean> - true when status is 'cleaned-up'
266​
267Parameters
268​
269- collection - Existing collection to observe directly
270- queryFn - Function that builds a static query using the query builder
271- options.params - Reactive function that returns parameters; triggers query rebuild when accessed signals change
272- options.query - Function that builds a query using parameters and query builder
273- config - Configuration object for creating a live query collection
274​
275Requirements
276​
277- Angular 16+ (requires signals support)
278- Must be called within an Angular injection context
279- Automatically handles cleanup when the injector is destroyed