Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions src/pages/snippets/stateful-standalone-component.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
title: NgRx Component Store Stateful Standalone Component
description: "Example of using Component store to add state to a component"
tags: ["angular", "ngrx", "state"]
pubDate: Feb 25, 2023
contributedBy: "@JayCooperBell"
---

Using NgRx Component Store to add state to a Component without an additional service.

```typescript
import { Component } from '@angular/core';
import { ComponentStore } from '@ngrx/component-store';
import { interval, Observable, tap } from 'rxjs';
import { AsyncPipe } from '@angular/common';

interface MyState {
counter: number;
}

@Component({
selector: 'my-stateful-component',
standalone: true,
template: ` <div>{{ counter$ | async }}</div>`,
imports: [AsyncPipe],
})
export class MyStatefulComponentComponent extends ComponentStore<MyState> {
readonly counter$ = this.select((state) => state.counter);

private readonly incrementCounter = this.updater((state) => ({
...state,
counter: state.counter + 1,
}));

private readonly incrementByInterval = this.effect(
(origin$: Observable<number>) =>
origin$.pipe(tap(() => this.incrementCounter()))
);

constructor() {
super({
counter: 0,
});

this.incrementByInterval(interval(1000));
}
}
```