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 @for (item of query.data(); track item.id) {
230 <div>{{ item.text }}</div>
231 }
232 } @else if (query.isError()) {
233 <div>Error loading data</div>
234 } @else {
235 <div>Loading...</div>
236 }
237
238API
239
240injectLiveQuery()
241
242Angular injection function for TanStack DB live queries. Must be called within an injection context (e.g., component constructor, inject(), or field initializer).
243
244Overloads
245
246 // Direct collection - reactive to collection changes
247 function injectLiveQuery<TResult, TKey, TUtils>(
248 collection: Collection<TResult, TKey, TUtils>
249 ): LiveQueryResult<TResult>
250
251 // Static query function - NOT reactive to signals within function
252 function injectLiveQuery<TContext>(
253 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>
254 ): LiveQueryResult<TContext>
255
256 // Reactive query with parameters - recreates when params() signals change
257 function injectLiveQuery<TContext, TParams>(options: {
258 params: () => TParams
259 query: (args: {
260 params: TParams
261 q: InitialQueryBuilder
262 }) => QueryBuilder<TContext>
263 }): LiveQueryResult<TContext>
264
265 // Collection configuration - static configuration
266 function injectLiveQuery<TContext>(
267 config: LiveQueryCollectionConfig<TContext>
268 ): LiveQueryResult<TContext>
269
270Returns
271
272An object with Angular signals:
273
274- data: Signal<Array<T>> - Array of query results, automatically updates
275- state: Signal<Map<Key, T>> - Map of results by key, automatically updates
276- collection: Signal<Collection> - The underlying collection instance
277- status: Signal<CollectionStatus> - Current status ('idle' | 'loading' | 'ready' | 'error' | 'cleaned-up')
278- isLoading: Signal<boolean> - true when status is 'loading'
279- isReady: Signal<boolean> - true when status is 'ready'
280- isIdle: Signal<boolean> - true when status is 'idle'
281- isError: Signal<boolean> - true when status is 'error'
282- isCleanedUp: Signal<boolean> - true when status is 'cleaned-up'
283
284Parameters
285
286- collection - Existing collection to observe directly
287- queryFn - Function that builds a static query using the query builder
288- options.params - Reactive function that returns parameters; triggers query rebuild when accessed signals change
289- options.query - Function that builds a query using parameters and query builder
290- config - Configuration object for creating a live query collection
291
292Requirements
293
294- Angular 16+ (requires signals support)
295- Must be called within an Angular injection context
296- Automatically handles cleanup when the injector is destroyed