Open History to see the last commit
1import { Component } from '@angular/core'
2import {
3 createAtom,
4 createStore,
5 createStoreContext,
6 injectAtom,
7 injectSelector,
8} from '@tanstack/angular-store'
9import type { Atom, Store } from '@tanstack/angular-store'
10β
11type CounterStore = {
12 cats: number
13 dogs: number
14}
15β
16const { provideStoreContext, injectStoreContext } = createStoreContext<{
17 votesStore: Store<CounterStore>
18 countAtom: Atom<number>
19}>()
20β
21@Component({
22 selector: 'app-root',
23 standalone: true,
24 providers: [
25 provideStoreContext(() => ({
26 votesStore: createStore<CounterStore>({
27 cats: 0,
28 dogs: 0,
29 }),
30 countAtom: createAtom(0),
31 })),
32 ],
33 template: `
34 <main>
35 <h1>Angular Store Context</h1>
36 <p>
37 This example provides both atoms and stores through Angular DI via
38 \`createStoreContext\`, then consumes them from the same component tree
39 with TanStack Store hooks.
40 </p>
41 <p>Cats: {{ cats() }}</p>
42 <p>Dogs: {{ dogs() }}</p>
43 <p>Total votes: {{ total() }}</p>
44 <div>
45 <button type="button" (click)="addCat()">Add cat</button>
46 <button type="button" (click)="addDog()">Add dog</button>
47 </div>
48 <section>
49 <h2>Nested Atom Components</h2>
50 <p>Atom count: {{ count() }}</p>
51 <div>
52 <button type="button" (click)="count.set((prev) => prev + 1)">
53 Increment atom
54 </button>
55 <button type="button" (click)="count.set(0)">Reset atom</button>
56 </div>
57 </section>
58 </main>
59 `,
60})
61export class AppComponent {
62 private ctx = injectStoreContext()
63β
64 cats = injectSelector(this.ctx.votesStore, (state) => state.cats)
65 dogs = injectSelector(this.ctx.votesStore, (state) => state.dogs)
66 total = injectSelector(
67 this.ctx.votesStore,
68 (state) => state.cats + state.dogs,
69 )
70 count = injectAtom(this.ctx.countAtom)
71β
72 addCat() {
73 this.ctx.votesStore.setState((prev) => ({
74 ...prev,
75 cats: prev.cats + 1,
76 }))
77 }
78β
79 addDog() {
80 this.ctx.votesStore.setState((prev) => ({
81 ...prev,
82 dogs: prev.dogs + 1,
83 }))
84 }
85}