2

I simply redirected to Profile page with router fragment (/profile#favorites) where favorite is a Bootstrap tab component. By default, first tab is active and favorite tab is 2 here in my case which I want to programmatically activate retriving fragment name from the url.

I got the fragment from url by:

this.activatedRoute.fragment.subscribe(fragment => {
  console.log('fragment : ', fragment);
});

My tabs structure is :

<ul class="nav nav-tabs">
    <li class="active"> <a data-toggle="tab" href="#myPets"> My Pets</a> </li>
    <li><a data-toggle="tab" href="#favorites">Favorites</a></li>
    <li *ngIf="!userDetails?.isSocialSiteUser">
    <a data-toggle="tab" href="#changePassword">Change Password</a>
    </li>
    <!-- <li><a data-toggle="tab" href="#account"> Account</a></li> -->
    <li> <a data-toggle="tab" href="#meets">Upcoming Meet and Greets</a> </li>
    <li> <a data-toggle="tab" href="#myDeals" *ngIf="myDeals.length">My Deals</a> </li>
</ul>

<div class="tab-content">
    <div id="myPets" class="tab-pane overflow-y-500-x-hide fade in active" #myPets>
    ...
    </div>

    <div id="favorites" class="overflow-y-500-x-hide tab-pane fade" #favorites>
    <sfl-profile-favorites></sfl-profile-favorites>
    </div>

    ...

</div>

Now I don't know how to activate the favorites tab. Maybe this can be achieved by toggling the in active class, but how can I remove from all other tabs and add to particular tab?

1 Answer 1

3

You can store fragment and apply active class condition in template file

this.activatedRoute.fragment.subscribe(fragment => {
  this.currentFragment = fragment //store somewhere
});

In template file [ngClass]="{'class': true}"

<li [ngClass]="{'active': currentFragment === '/profile#myPets'}">
    <a data-toggle="tab" href="#myPets"> My Pets</a> </li>

<li [ngClass]="{'active': currentFragment === '/profile#favorites'}">
    <a data-toggle="tab" href="#favorites">Favorites</a></li>

<div id="favorites" class="overflow-y-500-x-hide tab-pane fade" 
    [ngClass]="{'active': currentFragment === '/profile#favorites'}"
     #favorites>.....</div>
Sign up to request clarification or add additional context in comments.

4 Comments

Amazing! Very simple, but was out of my mind! Thanks!
One issue now facing is, when I open any other tab manually and then go to favorites programatically using fragment, the old tab content stays and favorites tab content is appended on top of it.
[update] I removed the data-toggle attributes from nav-tabs and instead, I put routerlink with fragment which then worked fine for me.
does anyone have stackblitz demo ?. Im trying with given solution . seems not working form me ..!! @Chenna

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.