Skip to content

Instantly share code, notes, and snippets.

@kuncevic
Created March 1, 2021 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuncevic/0dbd1c30bb5c7fa6d2904d021e955d02 to your computer and use it in GitHub Desktop.
Save kuncevic/0dbd1c30bb5c7fa6d2904d021e955d02 to your computer and use it in GitHub Desktop.
NGXS Data example.
<div class="wrapper">
<div class="title">
Child 👦
</div>
<div class="content">
<div class="action">
<button (click)="counter.updateValue2(-1)">-1</button>
<span class="value"> {{ counter.snapshot.value2 }}</span>
<button (click)="counter.updateValue2(1)">+1</button>
</div>
</div>
<app-little-child></app-little-child>
</div>
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { CounterDataState } from '../state/counter.state';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ChildComponent {
constructor(public counter: CounterDataState) {}
}
import { Injectable } from '@angular/core';
import { Computed, DataAction, Payload, StateRepository } from '@ngxs-labs/data/decorators';
import { NgxsDataRepository } from '@ngxs-labs/data/repositories';
import { State } from '@ngxs/store';
export interface Counter {
value1: number;
value2: number;
value3: number;
}
const initialState: Counter = { value1: 0, value2: 0, value3: 0 };
@StateRepository()
@State<Counter>({
name: 'counterData',
defaults: initialState,
})
@Injectable()
export class CounterDataState extends NgxsDataRepository<Counter> {
@DataAction()
public updateValue1(@Payload('value1') value1): void {
this.ctx.setState((state) => ({ ...state, value1: state.value1 + value1 }));
}
@DataAction()
public updateValue2(@Payload('value2') value2: number): void {
this.ctx.setState((state) => ({ ...state, value2: state.value2 + value2 }));
}
@DataAction()
public updateValue3(@Payload('value3') value3: number): void {
this.ctx.setState((state) => ({ ...state, value3: state.value3 + value3 }));
}
@Computed()
public get sum(): number {
return this.snapshot.value1 + this.snapshot.value2 + this.snapshot.value3;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment