Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8 - URL loads with routerLink but doesn't show when directly access in the browser in LOCALHOST

I have developed the Angular 8 application and I am using the routerLink to navigate the components which work fine without any issue but when I enter the same URL directly in the browser it doesn't show anything and in the console, I am seeing the errors as below

enter image description here

For Example, I open the homepage http://localhost:4200/home and I have added the routerLink here to go to http://localhost:4200/about and I will be able to view successfully but if I enter the URL http://localhost:4200/about directly in the ULR nothing shows

I have taken care of the app-routing.model.ts

const routes: Routes =
    [
        { path: 'home', component: HomeComponent },
        { path: 'about', component: AboutComponent },
        { path: '**', redirectTo: '/home', pathMatch: 'full' }
    ];
    @NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})

And I have header.component.ts to handle the navigation bar so I have added the <router-outlet></router-outlet> in the header.component.html and then I have included the selector of header.component.ts in app.component.ts <app-header></app-header> and then in finally index.html I have included the selector of app.component.ts i.e <app-root></app-root>

Can you please tell me if there is something wrong.

Before asking this question I have gone through below and nothing helps

  1. RouterLink does not work
  2. Angular 2 Routing Does Not Work When Deployed to Http Server
  3. Angular2 routing - url doesn't change and page doesn't load
like image 292
Mahesh G Avatar asked Aug 15 '19 14:08

Mahesh G


People also ask

How do I know if my routerLink is active?

routerLinkActive is simply an indicator of whether this link represents the active route. @jessepinho - Tried it - [routerLinkActive]="'active'" will only work if you also have [routerLink] in the a-tag. If you had (click)="navitageTo('/route')" instead of [routerLink], and in that function, you called this.

What is difference between routerLink and routerLink?

What is the difference between [routerLink] and routerLink ? How should you use each one? They're the same directive. You use the first one to pass a dynamic value, and the second one to pass a static path as a string.

What is the main difference between HREF and routerLink in an Angular application?

Href is the basic attribute provided by Html to navigate through pages which reloads the page on click. routerLink is the attribute provided by angular to navigate to different components without reloading the page.


1 Answers

On server we can use hashStrategy for routing.

In routing file just replace RouterModule.forRoot(routes) to RouterModule.forRoot(routes,{useHash : true}).

like image 51
aakash varshney Avatar answered Sep 19 '22 17:09

aakash varshney