简体   繁体   中英

How to add the content `…<span class=“sr-only”>(current)</span></a>` into the HTML link when using Angular 2 **routerLink**?

Just wanting to know how include <span class="sr-only">(current)</span> on my clicked active link when using Angular 2 routerLink ?

Example:

<ul class="nav nav-sidebar">
    <li routerLinkActive="active">
        <a routerLink="/dashboard">Dashboard <span class="sr-only">(current)</span></a>
    </li>
    <li>
        <a href="">Registers</a>
    </li>
    <li routerLinkActive="active">
        <a routerLink="/organizations">Organizations</a>
    </li>
</ul>

Sources: Twitter Bootstrap > Accessibility > Skip navigation ANgular 2 > ROUTING & NAVIGATION

In your component, you can add a method isActiveLink like

@Component({
  selector: 'my-app',
  template: `
<ul class="nav nav-sidebar">
    <li routerLinkActive="active">
        <a routerLink="/dashboard">
            Dashboard
            <span *ngIf="isActiveLink('/dashboard')" class="sr-only">(current)</span>
        </a>
    </li>
    <li>
        <a href="">Registers</a>
    </li>
    <li routerLinkActive="active">
        <a routerLink="/organizations">
            Organizations
            <span *ngIf="isActiveLink('/organizations')" class="sr-only">(current)</span>
        </a>
    </li>
</ul>
  `,
  styleUrls: ['app/app.component.css'],
})
export class AppComponent {

  isActiveLink(link:string) {
    return this.router.isActive(link);
  }

  constructor(private router:Router) {}
}

If you want just mark actually active route, you can just add routerLinkActive to directive (you did this), it adding class active to anchor tag, so you can simply style active link in css. If you have something like :

<ul class="nav nav-sidebar">
    <li routerLinkActive="active">
        <a routerLink="/dashboard">Dashboard <span class="sr-only">(current)</span></a>
    </li>
</ul>

you can simply style it, using this:

nav-sidebar li:active {
   background-color: #00CAFE;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM