【问题标题】:In Angular 9, how do you change the HTMl of a navigation link if you are on the URL it is pointing to?在 Angular 9 中,如果您在导航链接指向的 URL 上,如何更改导航链接的 HTMl?
【发布时间】:2021-04-29 13:11:48
【问题描述】:

对于我的 Angular 9 应用,我有一个简单的应用布局

<app-navbar></app-navbar>
<router-outlet></router-outlet>

导航栏组件的样子

<mat-toolbar color="primary">
  <mat-toolbar-row>
    <h1>My App</h1>
    <span class="menu-spacer"></span>
    <div>
      <a mat-button [routerLink]="'/'"> Home </a>
      <a mat-button [routerLink]="'/latest'"> Latest </a>
      <a mat-button [routerLink]="'/current'"> Items </a>
    </div>
  </mat-toolbar-row>
</mat-toolbar>

如果用户已经在该页面上,我试图弄清楚 Angular 的方法是将链接更改为文本而不是锚点。如果 URL 与我想要路由到的内容匹配,那么抑制链接生成并仅包含文本的正确方法是什么?

【问题讨论】:

标签: angular routes navigation angular9


【解决方案1】:

试试这个,我认为这就是你想要做的。 使用routerLinkActive指定自定义css类anchor-to-text

<a mat-button [routerLink]="'/'" routerLinkActive="anchor-to-text"> Home </a>

在您的导航栏组件 css 文件中编写我们自己的 css 以使锚标记看起来像纯文本

.anchor-to-text {
    cursor:text;
    color:inherit;
    text-decoration:none;
    pointer-events:none;
}

【讨论】:

    【解决方案2】:

    您可以通过订阅导航栏中的路由器事件来检查您当前的路线

    class NavbarComponent {
      constructor(private router: Router) {
        router.events.subscribe((val) => {
            console.log(val) 
        });
      }
    }
    

    https://angular.io/api/router/RouterEvent

    也许 ActivatedRoute 对你来说是一个更好的解决方案:

    export class NavbarComponent {
      constructor(private activatedRoute: ActivatedRoute) {
        activatedRoute.queryParams.subscribe(
          params => console.log('queryParams', params));
      })
    }
    

    【讨论】:

    • 可以,基本上这里的导航栏会接收路由器变化的数据,你可以从发出的信息中提取各种信息。
    猜你喜欢
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2020-07-16
    相关资源
    最近更新 更多