ngx-view-state
v5.0.0
Published
ngx-view-state is a library for managing the Loading/Success/Error states of views in Angular applications that use Ngrx or HttpClient
Maintainers
Readme
The ngx-view-state library is designed to simplify managing Loading/Success/Error states in Angular applications that use NgRx.
Overview
- Installation
- Usage with NgRx
- Usage ngxViewState directive
- Components customization
- Usage with HttpClient
- Key parts of the library
- Documentation
Stackblitz Example
Medium blog post
Installation
Run: npm install ngx-view-state
Usage With NgRx
1. Create view state feature and pass generic type for the error state
// view-state.feature.ts
import { createViewStateFeature } from 'ngx-view-state';
export const { viewStatesFeature, selectActionViewStatus, selectIsAnyActionLoading } = createViewStateFeature<string>();2. Provide the viewStateFeature and ViewStateEffect in the root
// app.config.ts
import { provideState, provideStore } from '@ngrx/store';
import { provideEffects } from '@ngrx/effects';
import { viewStatesFeature } from './store/view-state.feature';
import { ViewStateEffects } from 'ngx-view-state';
export const appConfig: ApplicationConfig = {
providers: [provideStore({}), provideState(viewStatesFeature), provideEffects(ViewStateEffects)],
};3. Register actions in your effect to mark them as view state actions
// todos.effects.ts
import { ViewStateActionsService } from 'ngx-view-state';
@Injectable()
export class TodosEffects {
constructor(
private actions$: Actions,
private viewStateActionsService: ViewStateActionsService
) {
this.viewStateActionsService.add([
{
startLoadingOn: TodosActions.loadTodos,
resetOn: [TodosActions.loadTodosSuccess],
errorOn: [TodosActions.loadTodosFailure],
},
{
startLoadingOn: TodosActions.addTodo,
resetOn: [TodosActions.addTodoSuccess],
errorOn: [TodosActions.addTodoFailure],
},
// Update and delete actions can be added in the same way
]);
}
}4. Create view state selectors
// todos.selectors.ts
import { selectActionViewStatus, selectIsAnyActionLoading } from '../../store/view-state.feature';
import { TodosActions } from './todos.actions';
// Select loading/error/idle status of the loadTodos action
export const selectTodosViewStatus = selectActionViewStatus(TodosActions.loadTodos);
// To display an overlay when any of the actions are loading
export const selectIsTodosActionLoading = selectIsAnyActionLoading(
TodosActions.addTodo,
TodosActions.updateTodo,
TodosActions.deleteTodo
);5. Make use of previously created selectors and dispatch the load action.
// todos.component.ts
import { selectTodos } from './store/todos.feature';
import { selectTodosViewStatus, selectIsTodosActionLoading } from './store/todos.selectors';
import { ViewStateDirective } from 'ngx-view-state';
@Component({
selector: 'app-todos',
imports: [ViewStateDirective],
templateUrl: './todos.component.html',
styleUrl: './todos.component.css'
})
export class TodosComponent {
public todos$ = this.store.select(selectTodos);
public viewState$ = this.store.select(selectTodosViewStatus);
public isOverlayLoading$ = this.store.select(selectIsTodosActionLoading);
constructor(private store: Store) {
this.store.dispatch(TodosActions.loadTodos());
}Usage ngxViewState directive
Import the ViewStateDirective in your component and pass the view state value to the directive.
<!-- todos.component.html -->
<ng-container *ngxViewState="viewState$ | async">
<table *ngIf="todos$ | async as todos" mat-table [dataSource]="todos">
// Render todos
</table>
<div class="loading-shade" *ngIf="isOverlayLoading$ | async">
<app-loading></app-loading>
</div>
</ng-container>Directive will then render the appropriate component based on the view state value.
Components customization
You can provide your own components by using the provideLoadingStateComponent and provideErrorStateComponent functions.
By default, the library uses the ngx-view-state components with simple template
// app.config.ts
import { provideLoadingStateComponent, provideErrorStateComponent } from 'ngx-view-state';
export const appConfig: ApplicationConfig = {
providers: [
// ...
provideLoadingStateComponent(LoadingComponent),
provideErrorStateComponent(ErrorComponent),
],
};Usage with HttpClient
mapToViewModel is a utility function that can be used to map the response of an HTTP request to a ComponentViewModel interface that is compatible with the ngxViewState directive.
import { mapToViewModel } from 'ngx-view-state';
@Injectable()
export class TodosService {
constructor(private http: HttpClient) {}
loadTodos(): Observable<ComponentViewModel<Todo[]>> {
return this.http.get<Todo[]>('https://jsonplaceholder.typicode.com/todos').pipe(mapToViewModel());
}
}And then in your component, you can use the ngxViewState directive to handle the view state of the HTTP request.
// todos.component.ts
import { TodosService } from './todos.service';
@Component({
selector: 'app-todos',
imports: [ViewStateDirective],
templateUrl: './todos.component.html',
styleUrl: './todos.component.css',
})
export class TodosComponent {
public todos$ = this.todosService.loadTodos();
constructor(private todosService: TodosService) {}
}<!-- todos.component.html -->
<ng-container *ngxViewState="todos$ as todos">
<table mat-table [dataSource]="todos.data">
// Render todos
</table>
</ng-container>You can also perform custom mapping by passing an object with onSuccess and onError handlers to the mapToViewModel function.
import { mapToViewModel } from 'ngx-view-state';
loadTodos(): Observable<ComponentViewModel<Todo[]>> {
return this.http.get<Todo[]>('https://jsonplaceholder.typicode.com/todos').pipe(
mapToViewModel({
onSuccess: (data) => ({ viewStatus: loadedViewStatus(), data: data.map(...) }),
onError: (error) => ({ viewStatus: errorViewStatus('Failed to load todos') })
})
);
}Key parts of the library
State management
createViewStateFeature(view-state.feature.ts)
Factory that creates an NgRx feature to manage view states for actions.
Generates selectors such asselectActionViewStatusandselectIsAnyActionLoading.ViewStateActions(view-state.actions.ts)
Defines actions for starting, resetting, or reporting errors in view states.ViewStateEffects(view-state.effects.ts)
Listens for configured actions and dispatches view-state actions to update the store.ViewStateActionsService– a service that maps specific actions to “start loading,” “reset,” or “error” behaviors. It exposes helpers like add, remove, and checks for a given action type. This service is typically injected in an NgRx effect to register which actions affect the view state
Directive for templates
ViewStateDirective
Allows components to display content, loading, or error components based on aViewStatusorComponentViewModel.
Reacts to status changes and renders the appropriate template, spinner, or error component.
Helpers and models
- Factory functions for constructing
ViewStatusvalues (loadingViewStatus,errorViewStatus, etc.). mapToViewModel
Helper to transform HTTP responses into a typed view model used by the directive.
Default components & customization
- Simple
LoadingStateComponentandErrorStateComponentare located incomponents/.
You can supply custom components via theprovideLoadingStateComponentorprovideErrorStateComponenttokens.
Documentation
- createViewStateFeature
- Selectors
- ViewStateActions
- ViewStateEffects
- ViewStatus
- ViewStateDirective
- provideLoadingStateComponent
- provideErrorStateComponent
- ViewStateErrorProps
- ComponentViewModel
- mapToViewModel
createViewStateFeature
Creates a feature that holds the view state of the actions.
State interface:
export interface ViewState<E> {
actionType: string;
viewStatus: ViewStatus<E>;
}Where E generic is the type of the error state.
actionTypeis the static type property of the action.viewStatusis the view state of the action.
Returns an object with the following properties:
initialState- Initial state of the view state feature.viewStatesFeatureName- Name of the view state feature.viewStatesFeature- NgRx feature that holds the view state of the actions.
Selectors:
selectViewStateEntities- returns the view state entities.selectViewStateActionTypes- returns the view state action types (TodosActions.loadTodos.type).selectAllViewState- returns all view states.selectActionViewStatus- returns the view status of the action.selectViewState- returns the view state entity by action type.selectIsAnyActionLoading- returns whether any of the provided actions are inLOADINGstate.selectIsAnyActionLoaded- returns whether any of the provided actions are inLOADEDstate.selectIsAnyActionError- returns whether any of the provided actions are inERRORstate.selectIsAnyActionIdle- returns whether any of the provided actions are inIDLEstate.
ViewStateActions
Action group to work with the view state reducer
export const ViewStateActions = createActionGroup({
source: 'ViewState',
events: {
startLoading: props<{ actionType: string }>(),
reset: props<{ actionType: string }>(),
resetMany: props<{ actionTypes: string[] }>(),
error: props<{ actionType: string; error?: unknown }>(),
errorMany: props<{ actionTypes: { actionType: string; error?: unknown }[] }>(),
},
});ViewStateEffects
An effect that listens to the actions and updates the view state of the action.
List of effects:
startLoading$- upsert the view state of the action toLOADING.reset$- resets many view state actions toIDLE.error$- upsert many view state actions toERROR.
reset$ and error$ effects reset or error multiple view states because one action can be used in many configuration and change the view state of multiple actions.
ViewStatus
A union type that represents the view state:
export interface ViewIdle {
readonly type: ViewStatusEnum.IDLE;
}
export interface ViewLoading {
readonly type: ViewStatusEnum.LOADING;
}
export interface ViewLoaded {
readonly type: ViewStatusEnum.LOADED;
}
export interface ViewError<E = unknown> {
readonly type: ViewStatusEnum.ERROR;
readonly error?: E;
}
export type ViewStatus<E = unknown> = ViewIdle | ViewLoading | ViewLoaded | ViewError<E>;factory functions:
idleViewStatus- returns the idle view status.loadingViewStatus- returns the loading view status.loadedViewStatus- returns the loaded view status.errorViewStatus- returns the error view status with an optional error payload.
ViewStateDirective
A structural directive that handles the view state of the component.
is compatible with the ComponentViewModel and ViewStatus interfaces.
Handles view status in the following way:
private viewStatusHandlers: ViewStatusHandlers<ViewStatus, T> = {
[ViewStatusEnum.IDLE]: () => {
this.createContent();
},
[ViewStatusEnum.LOADING]: () => {
this.createSpinner();
},
[ViewStatusEnum.LOADED]: () => {
this.createContent();
},
[ViewStatusEnum.ERROR]: ({ viewStatus }) => {
this.createErrorState(viewStatus.error);
},
};When using the AsyncPipe, the directive will render the spinner for the first time
if (value == null) {
this.viewContainerRef.clear();
this.createSpinner();
return;
}provideLoadingStateComponent
A utility functions that provides a custom loading component for the ViewStateDirective directive.
import { provideLoadingStateComponent } from 'ngx-view-state';
export const appConfig: ApplicationConfig = {
providers: [
// ...
provideLoadingStateComponent(LoadingComponent),
],
};provideErrorStateComponent
A utility functions that provides a custom error component for the ViewStateDirective directive.
import { provideErrorStateComponent } from 'ngx-view-state';
export const appConfig: ApplicationConfig = {
providers: [
// ...
provideErrorStateComponent(ErrorComponent),
],
};ViewStateErrorProps
An interface to implement the error state component.
@Component({
selector: 'ngx-error-state',
imports: [],
template: ` <h2>{{ viewStateError || 'There is an error displaying this data' }}</h2> `,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ErrorStateComponent implements ViewStateErrorComponent<string> {
@Input() public viewStateError?: string;
}ComponentViewModel
A generic interface that represents the view model of the component. Is used to handle the view state of the HTTP request along with mapToViewModel rxjs operator function.
import { ViewLoaded, ViewStatus } from './view-status.model';
export type ComponentViewModel<T, E = unknown> =
| { data?: T; viewStatus: Exclude<ViewStatus<E>, ViewLoaded> }
| { data: T; viewStatus: ViewLoaded };mapToViewModel
A utility function that maps the response of an HTTP request to a ComponentViewModel interface.
Accepts an object with onSuccess and onError handlers.
import { mapToViewModel } from 'ngx-view-state';
@Injectable()
export class TodosService {
constructor(private http: HttpClient) {}
loadTodos(): Observable<ComponentViewModel<Todo[]>> {
return this.http.get<Todo[]>('https://jsonplaceholder.typicode.com/todos').pipe(mapToViewModel());
}
}