File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 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+ ```
You can’t perform that action at this time.
0 commit comments