0

I have created this in the main.ts which gets the route url:

router: string;

constructor(private _router: Router) { 
    this.router = _router.url; 
}

This works well. Then in the main.html:

<app-main-menu *ngIf="router == '/'"></app-main-menu>
<app-item-list *ngIf="router == '/list'"></app-item-list>

<app-item-info *ngIf="router == '/:id'"></app-item-info> <!-- THIS DOES NOT WORK -->

When the route is /2 or /35 (or any number) I cannot get the app-item-info ngIf to work.

My question is, how can I set the *ngIf to show (true) when I always have a string " / " with a dynamic number " 345 " ?

Example: When the URL (route is ): localhost:4200/2 , the ngIf should display app-item-info.

EDIT: I cannot use <router-outlet> as I am using it for a different thing. Showing pages.

igor_c
  • 1,200
  • 1
  • 8
  • 20
IkePr
  • 900
  • 4
  • 18
  • 44
  • 2
    The problem is that you're comparing the `router` value with the string `'/:id'`, that's why it doesn't work. Also this approach looks like a very bad practice, try to refactor your code and use angular routing properly. – igor_c Nov 29 '19 at 15:12
  • I agree with @igor_c. This does not seem to be the best approach. If you want to get the route parameters, you might want to look into https://stackoverflow.com/questions/40560399/subscribing-to-route-params-and-data-in-angular-2 – Chif Nov 29 '19 at 15:50
  • Does this answer your question? [Subscribing to route params and data in Angular 2](https://stackoverflow.com/questions/40560399/subscribing-to-route-params-and-data-in-angular-2) – Chif Nov 29 '19 at 15:52
  • 1
    Did you know that you can have multiple ``s? https://stackoverflow.com/questions/38038001/multiple-named-router-outlet-angular-2 – user776686 Nov 29 '19 at 17:27

2 Answers2

2

I recommend to use <router-outlet> to implement this functionality. Check out the official Angular documentation about the routing: https://angular.io/guide/router

Live example: https://stackblitz.com/angular/aqqyljyojye

Milan Tenk
  • 2,415
  • 1
  • 17
  • 24
0

Can this help you?

<app-item-info *ngIf="isItemInfoRoute(router)"></app-item-info>

and in .ts

isItemInfoRoute(router: string) {
   return router.search(/^\/\d+/) > -1
}
Ashot Aleqsanyan
  • 4,252
  • 1
  • 15
  • 27