Search code examples
angularangular-ui-router

Angular routing changing # from url


I'm working with upgrading an AngularJs project into Angular 6. Earlier to open any page, I have used $state :

$state.transitionTo(stateName, {}, {reload: true});

Now in Angular routing has been introduced. I have made all required changes to open a page life-line-details page from a link added over the life-line page.

Changes are :

app.main.ts

export const routes: Route[] = [
    {
        path: 'life-line-details',
        component: LifeLineDetailsComponent
    }
];

@NgModule({
    imports: [
        RouterModule,
        BrowserModule,
        UpgradeModule,.....      
        RouterModule.forRoot(routes)
    ]

life-line.html

<td><a routerLink="/#/life-line-details"(click)="detailLifeLine(lLine)">Details</a></td>

life-line.component.ts

 detailLifeLine = function (lLine) { 
        this.router.navigateByUrl("/#/life-line-details");
    }

Also, I have trued navigate method. But won't worked.

life-line-details.html is a separate page should be opened from above actions and my project url should change to : http://192.168.1.12:8080/#/life-line-details but it changing to http://192.168.1.12:8080/%23/life-line-details

I tried to encodeURI and encodeURIComponent for the url passed to routerLink and navigate method. But none worked, I am unable to open the page due to %23 in place of #.

How can I resolve the issue?


Solution

  • In angular you just use the url as normal (without the hash upfront), if you want the router to use an hash infront of urls you need to use the HashLocationStrategy.

    So you have to change routerLink="/#/life-line-details" to routerLink="/life-line-details".

    And you can configure the router like this:

    RouterModule.forRoot(routes, {
      useHash: true,
    })