每次变量取值为init

时间:2018-04-24 16:27:19

标签: angular typescript angular5

我有一个包含3个元素的菜单,当我单击一个元素时,类值被更改为获取活动元素;但问题是,在一秒钟之后页面自动刷新并且类获得默认值,当然我得到了错误的元素Active。

HTML:

<nav class="nav nav-pills nav-fill">
  <a [class]="accueilClassValue" (click)="ChangeActiveMenu(1)" href="accueil">Accueil</a>
  <a [class]="proposeClassValue" (click)="ChangeActiveMenu(2)" href="propose">Proposer Un CoVoiturage</a>
  <a [class]="chercheClassValue" (click)="ChangeActiveMenu(3)" href="search">Chercher Un CoVoiturage</a>
</nav> 

TS:

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

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {


  constructor() { }

  ngOnInit() {
  }

  menuIndex = 1;
  accueilClassValue = "nav-item nav-link active";
  proposeClassValue = "nav-item nav-link";
  chercheClassValue = "nav-item nav-link";


  ChangeActiveMenu(index : number){
    this.menuIndex = index;

    if (this.menuIndex==1){
      this.accueilClassValue = "nav-item nav-link active";
      this.proposeClassValue = "nav-item nav-link";
      this.chercheClassValue = "nav-item nav-link";
    }
    else if (this.menuIndex==2){
      this.accueilClassValue = "nav-item nav-link";
      this.proposeClassValue = "nav-item nav-link active";
      this.chercheClassValue = "nav-item nav-link";
    }
    else if (this.menuIndex==3){
      this.accueilClassValue = "nav-item nav-link";
      this.proposeClassValue = "nav-item nav-link";
      this.chercheClassValue = "nav-item nav-link active";
    }
  }

}

1 个答案:

答案 0 :(得分:2)

你必须在这里使用routerLink而不是href。从代码中删除href并添加routerLink。 Angular动态生成其href。