首页 > 解决方案 > 按钮上的 routerLink 没有将我路由到该页面

问题描述

我之前已经这样做了数百次,但这次我做错了什么,我无法确定是什么。我在修改整个导航时遇到了这个问题。

手动手动路由确实有效。问题与路由设置无关,而仅与此组件有关,因为其他组件确实有效。自从重新设计我的组件后,我也没有对我的路由进行任何更改(在它不是这种动态之前)。

每当我单击此组件中的任何路由时,它只会停留在同一页面上,并且不会在视觉上做任何事情(甚至不会重新加载或向上滚动)。

我觉得我错过了一些明显的东西

我的代码

<div>
  <button color="primary" type="menu" mat-raised-button [matMenuTriggerFor]="routingMenu">
    <ng-container *ngFor="let screenType of ['mobile', 'desktop']">
      <mat-icon
        [attr.class]="screenType"
        [attr.inline]="screenType === 'desktop' ? true : false"
        >videogame_asset</mat-icon
      >
    </ng-container>
  </button>
  <mat-menu #routingMenu="matMenu">
    <ng-container *ngFor="let gmi of gameMenuItems">
      <button
        *ngIf="gmi.isVisible"
        type="menu"
        mat-menu-item
        [routerLink]="gmi.routerLink"
        (click)="gmi.onClick"
      >
        <mat-icon>{{ gmi.icon }}</mat-icon>
        <span>{{ gmi.name | translate }}</span>
      </button>
    </ng-container>
    <mat-divider></mat-divider>
    <button
      *ngFor="let mi of menuItems"
      type="menu"
      mat-menu-item
      [routerLink]="mi.routerLink"
    >
      <mat-icon>{{ mi.icon }}</mat-icon>
      <span
      [class]="currentPage === mi.routerLink ? 'current': ''">{{ mi.name | translate }}</span>
    </button>
  </mat-menu>
</div>
...
  get menuItems(): IMenuItem[] {
    return [
      {
        icon: "view_list",
        name: "Menu.UPCOMING_FEATURES",
        routerLink: ["/upcoming-features"],
      },
      {
        icon: "security",
        name: "Menu.PRIVACY_POLICY",
        routerLink: ["/privacy-policy"],
      },
    ];
  }
...

我试过的

生成的 HTML 的样子

<button
  _ngcontent-jyv-c138=""
  type="menu"
  mat-menu-item=""
  class="mat-focus-indicator mat-menu-item ng-star-inserted"
  tabindex="0"
  ng-reflect-router-link="/upcoming-features"
  role="menuitem"
  aria-disabled="false"
  style=""
>
  <mat-icon
    _ngcontent-jyv-c138=""
    role="img"
    class="mat-icon notranslate material-icons mat-icon-no-color"
    aria-hidden="true"
    >view_list</mat-icon
  ><span _ngcontent-jyv-c138="">Upcoming features</span>
  <div
    matripple=""
    class="mat-ripple mat-menu-ripple"
    ng-reflect-disabled="false"
    ng-reflect-trigger="[object HTMLButtonElement]"
  ></div>
</button>

标签: angularroutesangular-routing

解决方案


稍作休息,咬了一口,找到了解决办法。

我不得不用一个普通的 ( ) 属性替换我的get属性(对于我的菜单项) 。readonly这样它就不会get不断地执行。

我仍然不确定这是如何相互关联的,但它确实有效。所以我仍然愿意回答为什么会这样。

  readonly menuItems: IMenuItem[] =
    [
      {
        icon: "view_list",
        name: "Menu.UPCOMING_FEATURES",
        routerLink: ["/upcoming-features"],
      },
      {
        icon: "security",
        name: "Menu.PRIVACY_POLICY",
        routerLink: ["/privacy-policy"],
      },
    ];

推荐阅读