CodeMed
CodeMed

Reputation: 9191

Wildcard route for static content in Angular 7

I am learning Angular 7 by studying this example app. The example app uses a wildcard route to handle all otherwise-unhandled routes.

Specifically, this app-routing.module.ts directs all miscellaneous routes to AppConfig.routes.error404, which is handled by Error404PageComponent.ts, which then ultimately serves up error404-page.component.html for every possible route that is not specified by its own component and named route.

What specific changes would need to be made to the code in this sample app in order for the wildcard route serve different static content for different submitted routes?

For example, if a web user typed in the route /i-am-a-jelly-donut, what changes would need to be made so that the request would 1.) continue to go through Error404PageComponent.ts, but have the user's browser receive a new i-am-a-jelly-donut.page.html instead of the error404-page.component.html view?

The Error404PageComponent.ts would still serve up error404-page.component.html for every non-specified route. However, we would be adding logic to give special handling inside Error404PageComponent for a specific static route in addition to the logic for every non-specified route.

The goal here is to be able to handle static routes without having to create a separate component for each and every route. Think, for example, of a blog where most of the routes have an identical template, but with different content in each blog entry.

Upvotes: 0

Views: 332

Answers (1)

Adrian Brand
Adrian Brand

Reputation: 21638

Templates are compiled into the components at build time and you are not going to be able to change which template a component uses at runtime but you can hide and show sections based on conditions. Inject the router into your component

constructor(private router: Router) {}

Now you can set a variable on your component based on if the route contains 'i-am-a-jelly-donut'

jellyDonut = this.router.url.indexOf('i-am-a-jelly-donut') !== -1;

and in your template

<ng-container *ngIf="jellyDonut">
  Jelly Donut
</ngcontainer>

<ng-container *ngIf="!jellyDonut">
  Other stuff
</ngcontainer>

Upvotes: 1

Related Questions