niklas-wortmann / xstate-angular

POC Xstate Angular Implementation
13 stars 2 forks source link

xstate-ngx

This is just a POC while the PR in the Xstate Monorepository is being discussed. Eventually this will be moved and deprecated!

This package contains utilities for using XState with Angular.

Quick start

  1. Install xstate and xstate-ngx:
npm i xstate xstate-ngx
  1. Import the useMachine function:
import { useMachine } from 'xstate-ngx';
import { createMachine } from 'xstate';
import {Component, inject} from '@angular/core';
const toggleMachine = createMachine({
  id: 'toggle',
  initial: 'inactive',
  states: {
    inactive: {
      on: { TOGGLE: 'active' }
    },
    active: {
      on: { TOGGLE: 'inactive' }
    }
  }
});
const ToggleMachine = useMachine(toggleMachine, {providedIn: 'root'})
@Component({
  selector: 'app-toggle',
  standalone: true,
  imports: [],
  template: `<button (click)="toggleMachine.send({type: 'TOGGLE'})">
    {{
      toggleMachine.snapshot().value === 'inactive'
        ? 'Click to activate'
        : 'Active! Click to deactivate'
    }}
  </button>
  `,
  styleUrl: './toggle.component.css'
})
export class ToggleComponent {
  public toggleMachine = inject(ToggleMachine);
}

API

useActor(actorLogic, options?)

Returns { snapshot, send, actorRef }:

useMachine(machine, options?)

A function that returns an Injectable that creates an actor from the given machine and starts an actor that runs for the lifetime of the component or DI context.

Arguments

Returns { snapshot, send, actorRef }: