Elegant way to access the caption associated with

2019-08-19 00:56发布

问题:

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>