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