Search code examples
angulartypescriptangular7angular-routingangular7-router

Angular 2-7: What's the best approach of hiding/showing components on same URL?


Due to some platform restrictions, there I can't use Routing - different urls to navigate to different components.

In other words, there is only http://localhost.com/default

NO http://localhost.com/user

NO http://localhost.com/items

I manage to put all the child components in the AppComponent as a parent and use variables to indicate which child component to hide and show by ui actions in order to manipulate the layout.

<app-user-panel
  [hidden]="!showUser"
  (closed)="onUserPanelClosed($event)"
></app-user-panel>

<app-items-panel
  [hidden]="!showItems"
  (closed)="onItemsPanelClosed($event)"
></app-items-panel>

As there are massive components are put together, the code in ts file is messy.

I am wondering if there is any better approach of NOT using booleans and ngIf to show or hide child components?

RESOLUTION 1: Does Routing have an advanced feature to navigate to different components on same url?

RESULUTION 2: Use Routing params?


Solution

  • RESOLUTION 1: Does Routing have an advanced feature to navigate to different components on same url?

    Yes you can use hash location strategy instead. This way your pages are routed by only angular.

    Example: http://localhost.com/#/user Your server will not try to return a page for user, instead angular will evaluate it and render your user screen.

    The only thing you need to do is initing useHash with true

    @NgModule({
      imports: [ RouterModule.forRoot(routes, {useHash: true})],
      exports: [ RouterModule ]
    })
    

    This would be a better solution then looking into a cleaner way to hide and show components in one page.