|
| 1 | +--- |
| 2 | +title: NgRx Component Store Stateful Directive with Output |
| 3 | +description: "Example of using Component store in a directive to output state changes" |
| 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 Directive which then outputs that state to the parent. |
| 10 | + |
| 11 | +```typescript |
| 12 | +import { Directive, Output } from '@angular/core'; |
| 13 | +import { ComponentStore } from '@ngrx/component-store'; |
| 14 | +import { interval, Observable, tap } from 'rxjs'; |
| 15 | + |
| 16 | +interface MyState { |
| 17 | + counter: number; |
| 18 | +} |
| 19 | + |
| 20 | +@Directive({ |
| 21 | + selector: '[myStatefulDirective]', |
| 22 | + standalone: true, |
| 23 | +}) |
| 24 | +export class StatefulDirectiveWithOutputsDirective extends ComponentStore<MyState> { |
| 25 | + @Output() counterChange = this.select((state) => state.counter); |
| 26 | + |
| 27 | + private readonly incrementCounter = this.updater((state) => ({ |
| 28 | + ...state, |
| 29 | + counter: state.counter + 1, |
| 30 | + })); |
| 31 | + |
| 32 | + private readonly incrementByInterval = this.effect( |
| 33 | + (origin$: Observable<number>) => |
| 34 | + origin$.pipe(tap(() => this.incrementCounter())) |
| 35 | + ); |
| 36 | + |
| 37 | + constructor() { |
| 38 | + super({ |
| 39 | + counter: 0, |
| 40 | + }); |
| 41 | + |
| 42 | + this.incrementByInterval(interval(1000)); |
| 43 | + } |
| 44 | +} |
| 45 | +``` |
| 46 | + |
| 47 | +And then in your parent component you can use it like this: |
| 48 | + |
| 49 | +```typescript |
| 50 | +import { Component } from '@angular/core'; |
| 51 | +import { StatefulDirectiveWithOutputsDirective } from './stateful-directive-with-outputs.directive'; |
| 52 | + |
| 53 | +@Component({ |
| 54 | + standalone: true, |
| 55 | + selector: 'angular-snippet-examples-root', |
| 56 | + template: ` |
| 57 | + <div myStatefulDirective (counterChange)="counter = $event"> |
| 58 | + {{ counter }} |
| 59 | + </div> |
| 60 | + `, |
| 61 | + imports: [ |
| 62 | + StatefulDirectiveWithOutputsDirective, |
| 63 | + ], |
| 64 | +}) |
| 65 | +export class AppComponent { |
| 66 | + counter: number | null = null; |
| 67 | +} |
| 68 | +``` |
0 commit comments