Creating a Dynamic Reactive Angular Error Display Component

Ole Ersoy
2 min readFeb 28, 2021
Image by GUILHERME BERNARDO from Pixabay

Updated Version

There’s an updated version of this article here:

Scenario

We have defined an interface for error types:

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>

Approach

This is the complete implementation of our component:

import { Component, Input, OnInit } from "@angular/core";
import { Observable } from "rxjs";
import { ErrorTypes } from "./error.model";
@Component({
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 {

@Input()
error$: Observable<string>;
@Input()
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)">
...
</ng-container>

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);

Demo

--

--