Adrian
Adrian

Reputation: 3062

How to use router url wildcard in Angular 4?

I want to display my header component for every route that has /admin or routes that have these kind of urls /admin/dashboard , /admin/users, /admin/tasks or etc

app.component.html

<div id="page-wrap" class="inner-page {{router.url}}" *ngIf="router.url === '/admin'; else templateName">

  <app-header></app-header>

  <div class="page-content-wrap">

    <app-sidebar></app-sidebar>

    <div class="content-wrap panel-right">
        <router-outlet></router-outlet>
    </div>

  </div>

</div>

<ng-template #templateName>

  <div class="inner-page {{router.url}}">

    <div class="container">
        <flash-messages></flash-messages>
        <router-outlet></router-outlet>
    </div>

  </div>

</ng-template>

But the code above only accepts /admin. Do you know how can I add a wildcard so that it accepts routes that have /admin/tasks, /admin/users ?

This is the condition that needs to be improved:

<div id="page-wrap" class="inner-page {{router.url}}" *ngIf="router.url === '/admin'; else templateName">

Any help is appreciated.

Upvotes: 3

Views: 1487

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73731

You can write a method to check if the url is /admin or starts with /admin/:

isAdminRoute(value: string): boolean {
  return /^\/admin(\/|$)/.test(value);
}

and call it in the template:

<div *ngIf="isAdminRoute(router.url); else templateName" ...>

You can see the code at work in this stackblitz.


As an alternative, you could test the URL with the startsWith string method:

<div *ngIf="route.url === '/admin' || route.url.startsWith('/admin/'); else templateName" ... >

Upvotes: 6

Related Questions