Search code examples
angularcomponentshttp-status-code-404angular-ng-ifcode-reuse

use ngIf to reuse a component in case of error 404 , is possible? How to catch the error?


I have a root component in the app-routin.module.ts declared as HomeComponent, which I reuse in case of unknown route

const routes : Routes = [
{
  path: '',
  component: PrimaryComponent,
  data: { breadcrumb: 'PRIMARY'},
  children: [
    { path: '',
      component: HomeComponent,
      canActivate: [HomeGuard],
      pathMatch: 'full',
      data: {breadcrumb: 'Start'}
    },
    ....
    ....
    ....
    { path: '**',
      component: HomeComponent,
      data: {breadcrumb: 'Status Error'}
    }
   ]
 }
];

this fulfills its function by loading the same component with the breadcrumb changed.
And here comes my doubt. Inside the html of my HomeComponent I have a span that shows a welcome message on the main page and I would like to reuse all the layout and design to just modify that welcome message by an error message with a redirect link to the home.

I understand that it is possible to use a second span with a ngIf that shows the error message I referred to earlier. But, how can I capture the error to generate a condition for the ngIf? or is there some direct method of angular? Thank you very much in advance


Solution

  • Add to your route some data to recognize the error:

    { path: '**',
      component: HomeComponent,
      data: {
        breadcrumb: 'Status Error',
        error: 404
      }
    }
    

    in your HomeComponent ts:

    errorView: number;
    
    constructor(private activatedroute: ActivatedRoute){}
    
    ngOnInit() {
          const data = this.activatedroute.snapshot.data;
          if(data.hasOwnProperty('error')) {
            this.errorView = data.error;
          }
    }
    

    in your HomeComponent html:

    <div *ngIf="errorView === 404">no url matched</div>