如何将条件片段及其值添加到 Angular 中的锚点 html 标记 5

How to add conditional fragment with it's value to the anchor html tag in Angular 5

我正在从服务加载菜单,需要有条件地将片段添加到锚点。这里的问题是 fragment add # for the empty value 并且不想在 URL 中为空 fragment 添加 #。

请参阅以下 HTML 导航栏组件代码。

<ul class="nav navbar-nav">
    <li *ngFor="let menu of menus">
       <a [routerLink]="menu.menuUrl" [title]="menu.name" here need to add fragment with it's value if menu.fragment present>
          <span>{{menu.name}}</span>
       </a>
    </li>
</ul>

你可以做的是使用 ngSwitch 根据 menu.fragment

的值显示菜单
<ul class="nav navbar-nav">
  <li *ngFor="let menu of menus" [ngSwitch]="menu.fragment !== undefined">
    <a *ngSwitchCase="true" [fragment]="menu.fragment" [routerLink]="menu.menuUrl" [title]="menu.name">
      <span>{{menu.name}}</span>
    </a>
    <a *ngSwitchDefault [routerLink]="menu.menuUrl" [title]="menu.name" >
      <span>{{menu.name}} no frag</span>
    </a>
  </li>
</ul>

您可以找到一个 运行 示例 https://stackblitz.com/edit/angular-fxp2dx