in angular 7 i have define different component app folder and define component in route is well when i definde router name in url it,s work fine show me that component which is attached to that url but when i define that rout name in anchor tag click on anchor it,s not working here is my html code
<li class="nav-item">
<a class="nav-link" routerLink="/home">Home</a>
</li>
<li class="nav-item @@about">
<a class="nav-link" routerLink="/about">About</a>
</li>
<li class="nav-item @@blog">
<a class="nav-link" routerLink="/blog">BLOG</a>
</li>
this is my router
const routes: Routes = [{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'home',
component: HomeComponent
},
{
path: 'about',
component: AboutComponent
},
{
path: 'blog',
component: BlogComponent
},
];
If your anchor tag is not becoming blue that means routerLink is not binded with anchor tag. It is because you have not imported RouterModule
.
Note : You have to import RouterModule
in the the module where you have declared this component where you are adding routerLink
and not in the app.module.ts
. For example : if you have home.component.ts
in home.module.ts
and you want to use <a [routerLink]="[/student]"></a>
in home.component.html
then add RouterModule
in home.module.ts
import {RouterModule} from '@angular/router';
@NgModule(
{
...
import:[
...
RouterModule
...
]
...
}
)
In my angular 9 case, the component with links, was declared in a Shared Module. The RouterModule
was in the parent module. So the routerLink
did not work.
It worked when I imported the RouterModule
in the Shared Module also.
In case you are using ng serve
, you may have to restart it.
Try like this:
Define RouterModule like this:
RouterModule.forRoot([
{ path: 'home', component: HomeComponent },
{ path: 'blog', component: BlogComponent },
{ path: 'about', component: AboutComponent },
{ path: '**', redirectTo: 'home' }
])
Template:
<li class="nav-item">
<a class="nav-link" routerLink="/home">Home</a>
</li>
<li class="nav-item @@about">
<a class="nav-link" routerLink="/about">About</a>
</li>
<li class="nav-item @@blog">
<a class="nav-link" routerLink="/blog">BLOG</a>
</li>
<router-outlet></router-outlet>
Note: You must add <router-outlet></router-outlet>
Maybe You need just to add this to your app-routing.module :
const routerOptions: ExtraOptions = {
scrollPositionRestoration: 'enabled',
anchorScrolling: 'enabled',
scrollOffset: [0, 64],
};
and in your imports :
imports: [CommonModule, RouterModule.forRoot(routes, routerOptions)]
Scroll to top on Route Change in a simple way put in app.componenet.ts :
onActivate() {
window.scrollTo(0, 0);
}
app.component.html :
<router-outlet (activate)="onActivate()"></router-outlet>
styles.css
html {
scroll-behavior: smooth;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.