1

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?

2
  • Can you try <a href="home" [routerLink]="['/']" class="nav-link active">Home</a> Commented May 10, 2020 at 19:36
  • tried, it's the same result :( Commented May 10, 2020 at 19:39

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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.
];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.