Skip to content

Commit 744b68b

Browse files
authored
docs(ngrx): add component store stateful component example (#15)
* docs(ngrx): add example for stateful component store component * docs(ngrx): update example docs
1 parent 77d250f commit 744b68b

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
---
2+
title: NgRx Component Store Stateful Standalone Component
3+
description: "Example of using Component store to add state to a component"
4+
tags: ["angular", "ngrx", "state"]
5+
pubDate: Feb 25, 2023
6+
contributedBy: "@JayCooperBell"
7+
---
8+
9+
Using NgRx Component Store to add state to a Component without an additional service.
10+
11+
```typescript
12+
import { Component } from '@angular/core';
13+
import { ComponentStore } from '@ngrx/component-store';
14+
import { interval, Observable, tap } from 'rxjs';
15+
import { AsyncPipe } from '@angular/common';
16+
17+
interface MyState {
18+
counter: number;
19+
}
20+
21+
@Component({
22+
selector: 'my-stateful-component',
23+
standalone: true,
24+
template: ` <div>{{ counter$ | async }}</div>`,
25+
imports: [AsyncPipe],
26+
})
27+
export class MyStatefulComponentComponent extends ComponentStore<MyState> {
28+
readonly counter$ = this.select((state) => state.counter);
29+
30+
private readonly incrementCounter = this.updater((state) => ({
31+
...state,
32+
counter: state.counter + 1,
33+
}));
34+
35+
private readonly incrementByInterval = this.effect(
36+
(origin$: Observable<number>) =>
37+
origin$.pipe(tap(() => this.incrementCounter()))
38+
);
39+
40+
constructor() {
41+
super({
42+
counter: 0,
43+
});
44+
45+
this.incrementByInterval(interval(1000));
46+
}
47+
}
48+
```

0 commit comments

Comments
 (0)