How to create an 404 page?

When I try to navigate to a non-existing page through changing the contents of my browsers urlbar, I get redirected to the root of my application. But the homepage isn't rendered because core.js is throwing an generic error.

Now I have 2 questions:

  • Can I implement an 404 error page when routing fails? (before the automatic redirect)
  • Is the automatic redirect to the root on purpose? And if yes, why doesn't the page render? The users mistake of editing the address has already been countered by changing the address automatically.

Can I implement an 404 error page when routing fails? (before the automatic redirect)

Yes you can. Create a page in Radzen say called NotFound. Then open the app.module.ts file and modify it like this:

  1. Add these imports.
    import {routes} from './app.routes';
    import {RouterModule} from '@angular/router';
    
  2. Add this to the imports section of the AppModule declaration.
     RouterModule.forRoot([
       ...routes,
       {
         path: '**',
         redirectTo: 'not-found'
       }
     ])
    

This will make the Angular router navigate all unknown routes to the NotFound page. Here is the complete app.module.ts file:

import {NgModule} from '@angular/core';
import {ServiceWorkerModule} from '@angular/service-worker';
import {environment} from '../environments/environment';
import {
  AppImports,
  AppComponent,
  AppDeclarations,
  AppProviders
} from './app.module-generated';
import {routes} from './app.routes';
import {RouterModule} from '@angular/router';

@NgModule({
  declarations: [...AppDeclarations],
  imports: [
    environment.production
      ? ServiceWorkerModule.register('ngsw-worker.js')
      : [],
    RouterModule.forRoot([
      ...routes,
      {
        path: '**',
        redirectTo: 'not-found'
      }
    ]),
    ...AppImports
  ],
  providers: [...AppProviders],
  bootstrap: [AppComponent]
})
export class AppModule {}

Is the automatic redirect to the root on purpose? And if yes, why doesn't the page render?

This is the default behavior of the Angular router - to throw error when the current URL doesn't match any route.

We will consider adding out of the box support for that in one of the future Radzen versions.

2 Likes