Reputation: 525
I have a menu with 3 elements, when I click an element the classes values changed to get the active element; but the problem that after a second the page got refreshed automatically and the classes get the default value and of course I got the wrong element 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";
}
}
}
Upvotes: 1
Views: 41
Reputation: 3115
You will have to use routerLink instead of href here. Remove href from the code and add routerLink to it. Angular dynamically generates its href.
Upvotes: 2