Creating a Dynamic Reactive Angular Error Display Component

Image by GUILHERME BERNARDO from Pixabay

Updated Version

Scenario

export interface ErrorTypes {
[key: string]: string;
}
errorTypes: ErrorTypes = {
NETWORK_ERROR: "Network Error",
DATA_ERROR: "Data Error"
};
<fs-error [error$]="dataError$" [errorTypes]="errorTypes"></fs-error>

Approach

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);
}
}
<ng-container *ngIf="(error$ | async)">
...
</ng-container>
<ng-container *ngFor="let key of errorTypeKeys"><div *ngSwitchCase="key"><h3>{{ errorTypes[key] }}</h3></div>
<h3>{{ errorTypes[key] }}</h3>
this.errorTypeKeys = Object.keys(this.errorTypes);

Demo

Founder of Firefly Semantics Corporation