是否可以扩展此代码,例如有两个以上的选项?

问题描述 投票:0回答:1

这是我获取每个标题的代码:

export class WrapperComponent implements OnInit, OnDestroy {
  DASHBOARD = 'Dashboard'
  DASHBOARD_URL = 'dashboard'
  PERSONAL_INFORMATION = 'Personal Information'
  PERSONAL_INFORMATION_URL = 'personal-information'
  EMPLOYEE_HISTORY = 'Employee History'
  EMPLOYEE_HISTORY_URL = 'employee-history'
  navBarTitle = this.DASHBOARD
  subs: Subscription[] = [];
  constructor(private router: Router) {}

  ngOnInit(): void {
    this.subToRouterEvents();
  }

  ngOnDestroy(): void {
    if (0 === this.subs.length) {
      return;
    }
    this.subs.forEach((sub) => sub.unsubscribe());
  }

  subToRouterEvents() {
    const routeEventSub = this.router.events.subscribe(this.routerEventHandler);
    this.subs.push(routeEventSub);
  }

  routerEventHandler = (event: Event) => {
    if (event instanceof NavigationEnd) {
      const routeText = this.router.url.split('/');
      this.evalRouteUrl(routeText[3]);
    }
  };
  evalRouteUrl(url: string) {
    if ('undefined' === typeof url) return;
    this.navBarTitle = url === this.DASHBOARD_URL ? this.DASHBOARD : this.PERSONAL_INFORMATION
  }
}

这是我的 html 代码:

<nav aria-label="breadcrumb">
      <ol class="breadcrumb bg-transparent mb-0 pb-0 pt-1 px-0 me-sm-6 me-5">
        <li class="breadcrumb-item text-sm" *ngIf="navBarTitle === 'Personal Information'">
          <a class="opacity-5 text-white">My Account</a>
        </li>
        <li
          class="breadcrumb-item text-sm text-white active"
          aria-current="page" *ngIf="navBarTitle === 'Personal Information'"
        >
          My Profile
        </li>
        <li
          class="breadcrumb-item text-sm text-white active"
          aria-current="page"
        >
          {{ navBarTitle }}
        </li>
      </ol>
      <h6 class="font-weight-bolder text-white mb-0 text-uppercase">
        {{ navBarTitle }}
      </h6>
    </nav>

谁能帮我得到导航栏的标题……我有这段代码,但它只需要两个选项。这对我来说是一个很大的帮助。

是否可以扩展此代码,比如有超过 2 个选项?

 evalRouteUrl(url: string) {
    if ('undefined' === typeof url) return;
    this.navBarTitle = url === this.DASHBOARD_URL ? this.DASHBOARD : this.PERSONAL_INFORMATION
  }
node.js angular navbar title
1个回答
0
投票

请不要使用图像显示代码,否则编写代码,全选并使用 Ctrl+K 对其进行格式化(很难阅读带有图像的问题)

你应该“参数化你的应用程序”。那是使用一个对象数组

如果你有一个像这样的数组

paths=[{path:'dashboard', title:'Dashboard'},
       {path:'personal-information', title:'Personal Information'},
       ...
      ]

可以通过路径在数组中查找并返回标题

evalRouter(url:string)
{
   const path=this.paths.find(x=>x.path==url)
   this.navBarTitle=path?path.title:''
}

顺便说一句:您可以在Routes中使用new属性(从Angular 15开始-在以下版本中使用“数据”属性-)标题,例如

const routes=[{
  path: 'dashboard',
  component: DashboardComponent,
  title:'Dashboard'
}, {
  path: 'personal-information',
  component: PersonalInfoComponent,
  title:'Dashboard'
}
...
]
© www.soinside.com 2019 - 2024. All rights reserved.