我是Angular的新手,但遇到以下问题:
我有一个选项卡式用户界面
我的链接:
<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>
相应的标签内容:
<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>
在我的组件中:
@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();
}
}
当前网址是:
/dashboard/patient/view/1
如果我单击选项卡本身,则一切正常。但是,如果我使用这样的语句:
highlightTab('referrals');
它将URL更改为:
http://localhost:4200/#referrals
我在这里做错了什么? 需要更多代码吗?
答案 0 :(得分:2)
您不应使用href,它会重新加载页面Usefragment,并确保在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>
注入路由器并使用导航方法在路线之间导航,而不是使用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' } )
}
}