Reputation: 33368
I have the following routes defined:
const appRoutes: Routes = [
{ path: 'signup', component: SignupComponent },
{ path: 'home', component: HomeComponent },
{ path: '**', component: HomeComponent }
];
Accessing www.mysite.com
displays my HomeComponent
which is fine. But when I click my menu link to navigate back to the homepage it takes me to www.mysite.com/home
Link code below:
<a href="home" [routerLink]="['home']" class="nav-link active">Home</a>
How can I make this link navigate to the main url www.mysite.com
?
Upvotes: 1
Views: 6870
Reputation: 3566
You need to add route with empty string see example below
const appRoutes: Routes = [
{ path: 'signup', component: SignupComponent },
{ path: 'home', component: HomeComponent },
{ path: '', component: HomeComponent }
{ path: '**', component: HomeComponent }
];
In angular docs it's mentioned under property heading:
path?: string The path to match against. Cannot be used together with a custom matcher function. A URL string that uses router matching notation. Can be a wild card (**) that matches any URL (see Usage Notes below). Default is "/" (the root path).
and then update the link to:
<a href="home" [routerLink]="['/']" class="nav-link active">Home</a>
Upvotes: 2
Reputation: 3236
You are defining the home
route, and your link points to /home
, so the behavior is what you told Angular to do.
If you want to navigate to /
, change the html with <a [routerLink]="['/']" class="nav-link active">Home</a>
.
Also, you have to change your routing config:
const appRoutes: Routes = [
{ path: 'signup', component: SignupComponent },
{ path: 'home', component: HomeComponent },
{ path: '', component: HomeComponent, pathMatch: 'full' } // patchMath is important with empty route, otherwise any route would match
{ path: '**', redirectTo: '/' } // so if you want to access "/foo123", the url will change to "/", so the user wouldn't see a non existing url in the address bar.
];
Upvotes: 1