Angular2 default active link on site load

人走茶凉 提交于 2019-12-24 05:01:09

问题


I'm using angular2 and angular2 [routerLinkActive] on each link, to set the active link. This all works fine. When the user clicks on a link, the route becomes active and the link gets the "active" class injected and I can style accordingly.

However in the route setup I set up a default route like so:

const routes: Routes = [
{ path: '', redirectTo: 'gettiingstarted', pathMatch: 'full' },

This works in as far as the page now successfully loads the "gettingstarted" component when the user first navigates to the page, but unfortunately the router link has not had the "active" class injected at this point, so is not correctly styled. The only way to get the active class is to actually click the link.

Does anyone know how I can get [routerLinkActive] mechanism to work on page load?

Update Here is the code html for the link itself:

 <a [routerLink]="['gettingstarted']" [routerLinkActive]="['active']">

回答1:


Putting the following in the constructor of the app.component.ts file fixed it:

        this.router.navigate(['/gettingstarted']);

Not sure it is the recommended solution, but fixes it for my case.



来源:https://stackoverflow.com/questions/43585445/angular2-default-active-link-on-site-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!