import { Component , ComponentFactory , ComponentFactoryResolver , ComponentRef , OnDestroy , OnInit , ViewChild , ViewContainerRef } from '@angular/core' ; import { ActivatedRoute } from '@angular/router' ; import { PreviousRouteService } from '../services/previous-route.service' ; import { Subscription } from 'rxjs' ; import { errorComponents } from './error.list' ; @ Component ( { templateUrl : './error.component.html' , styleUrls : [ './error.component.scss' ] } ) export class ErrorComponent implements OnInit , OnDestroy { @ ViewChild ( 'errorContainer' , { read : ViewContainerRef , static : true } ) public errorContainer ; private componentRef : ComponentRef < any > ; public previousUrl : string ; private statusCodeSubscription : Subscription ; private readonly defaultStatusCode : number = 404 ; public statusCode : number = this . defaultStatusCode ; constructor ( private route , private resolver , private prevRouteService ) { this . statusCodeSubscription = this . route . params . subscribe ( params => this . statusCode = params . statusCode ) ; } public ngOnInit ( ) { this . createErrorComponent ( this . statusCode ) ; this . previousUrl = this . prevRouteService . getPreviousUrl ( ) ; } private createErrorComponent ( statusCode ) { const factory = this . resolver . resolveComponentFactory ( errorComponents [ statusCode ] ) ; this . componentRef = this . errorContainer . createComponent ( factory ) ; } public ngOnDestroy ( ) { this . errorContainer . clear ( ) ; this . componentRef . destroy ( ) ; this . statusCodeSubscription . unsubscribe ( ) ; } }