Open History to see the last commit
1import { Component } from '@angular/core'
2import { createStore, injectSelector } from '@tanstack/angular-store'
3β
4// Optionally, you can create stores outside of Angular components at module scope
5const petStore = createStore({
6 cats: 0,
7 dogs: 0,
8})
9β
10@Component({
11 selector: 'app-root',
12 standalone: true,
13 template: `
14 <main>
15 <h1>Angular Store Hooks</h1>
16 <p>
17 This example creates a module-level store. Components read state with
18 \`injectSelector\` and update it directly with \`store.setState\`.
19 </p>
20 <p>Cats: {{ cats() }}</p>
21 <p>Dogs: {{ dogs() }}</p>
22 <p>Total votes: {{ total() }}</p>
23 <div>
24 <button type="button" (click)="addCat()">Add cat</button>
25 <button type="button" (click)="addDog()">Add dog</button>
26 </div>
27 </main>
28 `,
29})
30export class AppComponent {
31 cats = injectSelector(petStore, (state) => state.cats)
32 dogs = injectSelector(petStore, (state) => state.dogs)
33 total = injectSelector(petStore, (state) => state.cats + state.dogs)
34β
35 addCat() {
36 petStore.setState((prev) => ({
37 ...prev,
38 cats: prev.cats + 1,
39 }))
40 }
41β
42 addDog() {
43 // directly update values in the store
44 petStore.setState((prev) => ({
45 ...prev,
46 dogs: prev.dogs + 1,
47 }))
48 }
49}