Angular6-routerLink根据我所在的页面更改内容

时间:2018-09-30 15:36:03

标签: angular typescript routerlink

我目前正在学习Angluar6,现在有点泡菜。 当前布局如下:

homescreen

如果我按任意按钮,我将转到他们的页面:

/help
/leaderboards
/maingame

这就是我现在想做的。我通过“帮助”按钮给出一个例子。这也应适用于右边的“排行榜”按钮。

  1. 如果我按下按钮,我应该转到“ /帮助”
  2. 将该按钮的类别更改为“ activeBtn”(基本上使按钮变暗)
  3. 将图标从“帮助”图标更改为“取消”图标
  4. 将该按钮的链接从“ / help”更改为“ /”(返回到根目录)
  5. 如果我按了其他任何按钮,那么我按的新按钮应该可以执行上面刚刚写的操作,但其他所有按钮都应恢复为默认状态(常规帮助图标,常规链接)。

这是我的HTML外观:

<div class="containerBtn">
  <div class="helpDiv">
    <button id="helpBtn" class="secondary" [routerLink]="['/help']" routerLinkActive="activeBtn">
      <i class="material-icons">{{ helpBtnIcon }}</i>
    </button>
  </div>
  <div class="leaderboardDiv">
    <button id="leaderboardsBtn" class="secondary" (click)=goToLeaderboards() routerLinkActive="activeBtn">
      <i class="material-icons">{{ leaderboardsBtnIcon }}</i>
    </button>
  </div>
  <div class="startDiv">
    <button id="startBtn" class="primary" [routerLink]="['/maingame']">
      Start
    </button>
  </div>
</div>

如您所见,最初我将routerLink与routerLinkActive一起使用。现在,我正在测试执行一个方法的click事件。但是,这会忽略routerLinkActive。

这是我的TS文件:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.css']
})

export class NavigationComponent implements OnInit {

  currentUrl: string;

  helpBtnIcon = 'help';
  leaderboardsBtnIcon = 'view_headline';
  cancelBtnIcon = 'cancel';

  constructor(private router: Router) {
    this.router.events.subscribe(value => {
      this.currentUrl = router.url.toString();

      if (this.currentUrl === '/help') {
        this.helpBtnIcon = this.cancelBtnIcon;
      } else {
        this.helpBtnIcon = 'help';
      }

    });
  }

  ngOnInit() {
  }

  goToLeaderboards() {
    this.router.navigate(['/leaderboards');
    this.leaderboardsBtnIcon = this.cancelBtnIcon;
  }

}

所以我对我想做的正确方法有些困惑。 一个问题是我将ICON更改为该“取消”图标,但是,如果我转到另一个页面,则我的按钮仍为X,并且不会切换回原始样式和图标及链接。

谢谢你们的帮助!

0 个答案:

没有答案