Creating a Dynamic Reactive Angular Error Display Component

Image by GUILHERME BERNARDO from Pixabay

Updated Version


export interface ErrorTypes {
[key: string]: string;

We want an Angular Component that can display an enumeration of error types defined by the ErrorTypes interface when the components error$:Observable<string> emits an error key.

For example we may implement the interface like this:

errorTypes: ErrorTypes = {
NETWORK_ERROR: "Network Error",
DATA_ERROR: "Data Error"

Note that the ErrorTypes instance values will be used to display the type of error that occurred in the components template.

Create the dataError$:Observable<string> = of('DATA_ERROR') .

And trigger data error display like this:

<fs-error [error$]="dataError$" [errorTypes]="errorTypes"></fs-error>


import { Component, Input, OnInit } from "@angular/core";
import { Observable } from "rxjs";
import { ErrorTypes } from "./error.model";
selector: "fs-error",
template: `
<ng-container *ngIf="(error$ | async)"><div [ngSwitch]="error$ | async"><ng-container *ngFor="let key of errorTypeKeys"><div *ngSwitchCase="key"><h3>{{ errorTypes[key] }}</h3></div></ng-container><div *ngSwitchDefault>The error key had no matches</div></div></ng-container>`,styles: []
export class ErrorComponent implements OnInit {

error$: Observable<string>;
errorTypes: ErrorTypes;
errorTypeKeys: string[];
ngOnInit() {
this.errorTypeKeys = Object.keys(this.errorTypes);

We render the error template if an error occurs:

<ng-container *ngIf="(error$ | async)">

We generate the dynamic switch conditions like this:

<ng-container *ngFor="let key of errorTypeKeys"><div *ngSwitchCase="key"><h3>{{ errorTypes[key] }}</h3></div>

The error that occurred is displayed via this part of the template:

<h3>{{ errorTypes[key] }}</h3>

Dynamic generation of the string[] array of possible error conditions ( this.errorTypeKeys ) is done by the ErrorComponent inside the ngOnInit life cycle method:

this.errorTypeKeys = Object.keys(this.errorTypes);




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store