Elegant way to access the caption associated with a router link in Angular

半腔热情 提交于 2019-12-25 14:57:22

问题


I'm wanting to display the currently selected link caption where the text Page Title currently is and wondered if there was an elegant way to do it.

import { Component } from '@angular/core';

@Component({
  template: `<div class="container">
  <div class="sub-navigation">
     <h1>Page Title </h1>
     <nav>
        <ul>
           <li *ngFor="let item of settingsMenu"><a [routerLink]="item.link"
            routerLinkActive="router-link-active"
            #rla="routerLinkActive"
            href=""><i ngClass="{{item.style}}" aria-hidden="true"></i> {{item.caption}} {{ rla.isActive ? '*' : ''}}</a></li>
        </ul>
      </nav>
          </div>
  <router-outlet></router-outlet></div>`,
})
export class SettingsComponent {
  settingsMenu = [
    // {caption:"Clients", link:['clients']},
    { caption: "Location Summary", link: ['locations'] },
    { caption: "Airports", link: ['airports'] },
    { caption: "Preferred Airlines", link: ['airports'] }
  ];
}

回答1:


That is what I did in my application. Not sure if it is an elegant way.

I have a service which has leftNavItems and selectedNavItem.

@Injectable()
export class WebUiService {
    leftNavItems: NavItem[] = [];
    selectedNavItem: NavItem = { id: -1, iconClass: '', title: '', displayName: '', routeUrl: '', primePermissionId: 0 };

    leftNavTo(itemId: number) {
        this.selectedNavItem = $.grep(this.leftNavItems, function (a) {
            return a.id === itemId;
        })[0];
    }
}

export class NavItem {
    id: number;
    iconClass: string;
    title: string;
    displayName: string;
    routeUrl: string;
    primePermissionId: number;
}

In actual route component, inject WebUiSerivce:

constructor(private webuiSvc: WebUiSerivce) {
    this.webuiSvc.leftNavTo(1);
}

In left menu component, inject WebUiService:

    <li *ngFor="let item of webuiSvc.leftNavItems" [class.active]="item == webuiSvc.selectedNavItem">
        <a [routerLink]="[item.routeUrl]" title="{{item.title}}">
            <i class="fa {{item.iconClass}}"></i> 
            <span class="nav-label">{{item.displayName}}</span>
            <span class="label label-primary pull-right" style="background-color:#3279b7">NEW</span>
        </a>
    </li>

In master layout, inject WebUiService:

    <div style="font-size:28px; font-weight:bold; float:left;padding:9px 0px 0px 30px; color:#fff;">
        <i class="fa {{webuiSvc.selectedNavItem?.iconClass}}"></i> {{webuiSvc.selectedNavItem?.title}}
    </div>

    <router-outlet></router-outlet>


来源:https://stackoverflow.com/questions/43826897/elegant-way-to-access-the-caption-associated-with-a-router-link-in-angular

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