Skip to content

Instantly share code, notes, and snippets.

@leandro-hermes
Last active September 28, 2020 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leandro-hermes/448be906ae61b3375d674c80afb20d66 to your computer and use it in GitHub Desktop.
Save leandro-hermes/448be906ae61b3375d674c80afb20d66 to your computer and use it in GitHub Desktop.
Generic component to show app-standardized error messages
import { Component, Optional } from '@angular/core';
import { ErrorDirective } from './error.directive';
@Component({
selector: 'display-error',
template: `
<img src="/assets/img/bug.svg">
<h2 #content class="mat-h2"><ng-content></ng-content></h2>
<h2 class="mat-h2" [innerHTML]="directive?.errorMessage" *ngIf="!content.innerText"></h2>
`,
styles: [
`
:host {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
box-sizing: border-box;
width: 100%;
height: 100%;
}
img {
display: block;
width: 64px;
filter: invert(.25);
}
`,
],
})
export class DisplayErrorComponent {
constructor(@Optional() public directive: ErrorDirective) {}
}
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DisplayErrorComponent } from './display-error.component';
import { ErrorDirective } from './error.directive';
@NgModule({
declarations: [DisplayErrorComponent, ErrorDirective],
exports: [DisplayErrorComponent],
imports: [CommonModule],
})
export class DisplayErrorModule {}
import { Directive, Input, OnChanges, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[error]',
})
export class ErrorDirective implements OnChanges {
private _view = null;
@Input('error')
public errorMessage: string | null;
constructor(private _tplRef: TemplateRef<any>,
private _viewContainer: ViewContainerRef) {
}
/**
*
*/
public ngOnChanges(): void {
if (this.errorMessage && !this._view) {
this._view = this._viewContainer.createEmbeddedView(this._tplRef);
} else if (!this.errorMessage && this._view) {
this._view = this._viewContainer.clear();
}
}
}
import { Component } from '@angular/core';
@Component({
selector: 'example',
template: `<display-error *error="theError"></display-error>`,
})
export class ExampleComponent {
public theError = 'Filed to fetch!';
}
@leandro-hermes
Copy link
Author

The image referenced here must exist on assets path

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment