Reducer Hook

It is how useReducer hook would look in Angular.

⚡️Reducer Hook in Template

An example in COMPONENT.component.ts.

@Component({
  selector: 'app-use-reducer',
  templateUrl: './use-reducer.component.html'
})
export class UseReducerComponent implements OnInit {

  initialAction = {
    type: 'reset',
    payload: 100
  };

  defaultState = {
    count: 0
  };

  reducer = (state, action) => {
    switch (action.type) {
      case 'reset':
        return { count: action.payload };
      case 'increment':
        return { count: state.count + 1 };
      case 'decrement':
        return { count: state.count - 1 };
      default:
        // A reducer must always return a valid state.
        // Alternatively you can throw an error if an invalid action is dispatched.
        return state;
    }
  }

}

An example in COMPONENT.template.html.

<ng-container *useReducer="
  let store init reducer
            with defaultState
            and initialAction">
	Count: {{ store.state.count }}
	<button (click)="store.dispatch({ type: 'reset', payload: 0 })">
    Reset 🔥
  </button>
  <button (click)="store.dispatch({ type: 'increment' })">
    Increment 🔥
  </button>
  <button (click)="store.dispatch({ type: 'decrement' })">
    Decrement 🔥
  </button>
</ng-container>

⚡️Reducer Hook with Ivy

An example in COMPONENT.component.ts.

function reducer(state, action) {
  switch (action.type) {
    case 'reset':
      return { count: action.payload };
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      // A reducer must always return a valid state.
      // Alternatively you can throw an error if an invalid action is dispatched.
      return state;
  }
}

@Component({
  selector: 'app-use-reducer',
  template: `
    Count: {{ state.count }}
    <button (click)="dispatch({ type: 'reset', payload: 0 })">
      Reset 🔥
    </button>
    <button (click)="dispatch({ type: 'increment' })">
      Increment 🔥
    </button>
    <button (click)="dispatch({ type: 'decrement' })">
      Decrement 🔥
    </button>
  `
})
@UseReducer(['state', 'dispatch'], reducer, { count: 0 })
class Host {}

Last updated