I'm using angular4 and trying to create a router link. The router link works but displays the template twice.
Below is my code in the component:
import { Component } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-root',
template: `
<h1>Contacts App</h1>
<ul>
<li><a [routerLink]="['/facebook/top']">Contact List</a></li>
</ul>
<router-outlet></router-outlet>
`
})
export class AppComponent {
constructor(
private route: ActivatedRoute,
private router: Router,
){ }
gotoDetail(): void {
this.router.navigate(['facebook/top']);
}
}
my routes:
const routes: Routes = [
{ path: '', component: AppComponent },
{ path: 'facebook/top', component: CommentComponent },
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
Your default route points to AppComponent
, so your route is rendering the AppComponent
inside the AppComponent
.
Create a DashboardComponent
or HomeComponent
for this. And then do:
{ path: '', component: DashboardComponent }
Update 1:
As @GünterZöchbauer mentioned, we should add pathMatch: 'full'
for "an empty path route with no children".
So we can go with the AppComponent
approach (check Günter's answer):
{ path: '', component: AppComponent, pathMatch: 'full' }
Or, the DashboardComponent
approach as I stated above in my answer.
Why is this happening?
1) In your application entry point, most likely main.ts
, one can read this line:
platformBrowserDynamic().bootstrapModule(AppModule);
This tells angular to bootstrap the module AppModule
2) In AppModule, one can find this line:
bootstrap: [ AppComponent ]
This tells angular to bootstrap the component AppComponent. This is why you see the first Contacts App part, because the html template of the AppComponent is:
<h1>Contacts App</h1>
<ul>
<li><a [routerLink]="['/facebook/top']">Contact List</a></li>
</ul>
<router-outlet></router-outlet>
3) However, the template of your AppComponent also contains <router-outlet>
. The router reads the routes configuration, accordingly creates a new instance of AppComponent and inject it right after the element <router-outlet>
. This is why you see the second Contacts App part.
If you have an empty path route with no children, use pathMatch: 'full'
instead of
{ path: '', component: AppComponent },
use
{ path: '', component: AppComponent, pathMatch: 'full' },
and what @SrAxi said.
In your app-routing.module.ts file try to use:
{path: '' , redirectTo: 'AppComponent', pathMatch: 'full'}
instead of:
{ path: '', component: AppComponent, pathMatch: 'full' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With