Reputation: 1097
I am looking to create nav links that look like file folder tabs by adding and removing class with angular. When a link is active, it will not have a bottom border so it appears to be the primary tab. Here's a rough beginning:
How can I correctly use [ngClass] to add and remove classes to my links given these questions?
Problem 1: how to implement a hover directive? I want the non-active link to shade grey when hovered over
Problem 2: How to add the 'active-link' class to one of them by default, so that on initial load it appears active (no bottom border)
What I have so far-
my component.html:
<ul class="nav nav-tabs">
<li [ngClass]="{'active-link': id === 1 }" id="1"(click)="addClass(id=1)" ><a [routerLink]="['']" data-toggle="tab">All Sites</a></li>
<li [ngClass]="{'active-link': id === 2 }" id="2"(click)="addClass(id=2)"><a [routerLink]="['/sites/map']" data-toggle="tab">Sites Map</a></li>
</ul>
My component.css:
li {
display: inline;
font-size: 150%;
}
.active-link {
border-bottom: 1px solid black;
}
.nav li {
border-radius: 3px;
border-top: 1px solid black;
border-left: 1px solid black;
border-right: 1px solid black;
}
And for my .ts file
export class AppComponent {
addClass(id: any) {
this.id = id;
}
...
What can I change/add to my code to cleanly add the 'active-link' by default, as well as a hover directive for the non-active link?
Thanks! Let me know if I can clarify
Upvotes: 0
Views: 1933
Reputation: 3683
You can have a property like selectedTab
which is what i'm guessing id
is doing here. Just have all tabs have the unselected/inactive class and apply the active class only if the selectedTab
/id
is equal to that tabs id, you don't need ngClass
if you don't want it you can write [class.active-link]="id === 1"
where one is that links id. Set the variable id
to your default tab in ngOnInit
(or in the constructor or default in the class). If I'm missing something here let me know.
As for your hover issue, How can I add a class to an element on hover?
.ts file:
export class AppComponent {
selectedTab = 0;
constructor() {}
// Function to select a tab.
selectTab(tabId: number) {
this.selectedTab = tabId;
}
}
.html file:
<ul class="nav nav-tabs">
<li [class.active-link]="selectedTab === 0" (click)="selectTab(0)"><a data-toggle="tab">All Sites</a></li>
<li [class.active-link]="selectedTab === 1" (click)="selectTab(1)"><a data-toggle="tab">All Sites</a></li>
</ul>
Upvotes: 2