Ashutosh
Ashutosh

Reputation: 4675

Angular 6: Clicking from component causes href value to add on URL

I am new to Angular and stuck in following problem:

I have a tabbed UI

My link:

<li>
  <a href="#referrals" id="tab-opinions" data-toggle="tab" target="_self" #referrals> 
   <span class="visible-xs"><i class="fa fa-home"></i></span>
   <span class="hidden-xs">Referrals</span> 
  </a>
</li>
<li>
  <a href="#opinions" id="tab-opinions" data-toggle="tab" target="_self" #opinions> 
   <span class="visible-xs"><i class="fa fa-home"></i></span>
   <span class="hidden-xs">Opinions</span> 
  </a>
</li>

Corresponding tab content:

<div class="tab-pane" id="referrals">
     <referral-list [data]="data"></referral-list>
</div>
<div class="tab-pane" id="opinions">
     <doctor-opinion-list [data]="data"></doctor-opinion-list>
</div>

In my component:

@ViewChild("opinions") private opinions;
@ViewChild("referrals") private referrals;

...
...

/* Highlights a particular tab with given id */
highlightTab(tabId) {
  if (["referrals"].indexOf(tabId) > -1) {
    this.referrals.nativeElement.click();
  } else if (["opinions"].indexOf(tabId) > -1) {
    this.opinions.nativeElement.click();
  }
}

Current URL is:

/dashboard/patient/view/1

If I click on tab itself, everything works fine. But if I use statement like this:

highlightTab('referrals');

It changes the URL to:

http://localhost:4200/#referrals

What am I doing wrong here? Any more code required?

Upvotes: 0

Views: 130

Answers (1)

Chellappan வ
Chellappan வ

Reputation: 27409

you should not use href it will reload the page Use fragment and make sure you enable anchor scrolling in routerModule

router.module.ts

RouterModule.forRoot(routes, {        
      anchorScrolling: 'enabled'
    })

component.html

<li>
  <a  [fragment]="'referrals'" id="tab-opinions" data-toggle="tab" target="_self" #referrals> 
   <span class="visible-xs"><i class="fa fa-home"></i></span>
   <span class="hidden-xs">Referrals</span> 
  </a>
</li>
<li>
  <a [fragment]="'opinions'" id="tab-opinions" data-toggle="tab" target="_self" #opinions> 
   <span class="visible-xs"><i class="fa fa-home"></i></span>
   <span class="hidden-xs">Opinions</span> 
  </a>
</li>

Inject Router and use navigate method to navigate between route instead of using ViewChild

constructor( private router: Router ) {}
}
highlightTab(tabId) {
  if (["referrals"].indexOf(tabId) > -1) {
    this.router.navigate( [ 'path name' ], { fragment: 'referrals' } )
  } else if (["opinions"].indexOf(tabId) > -1) {
    this.router.navigate( [ 'path name' ], { fragment: 'opinions' } )
  }
}

Upvotes: 2

Related Questions