Tabbar and Angular 2
Hi! I am using Onsen UI 2 and Angular 2. I have a page with ons-tabbar and two tabs, I want to set active tab when ngOnInit() called, but I don’t know how to get instance of OnsTabbar component. I looked at the sources of ons-tabbar.ts and saw there only ons-tab directive.
Please, help me in my question.
@Aleksandr-Pchelin Can’t you just set the
activeattribute on the tab you wish to load as default?
@misterjunio Hi! I want set active tab with value of query string parameter.
@Aleksandr-Pchelin I was able to find a solution. You can access the
tabbarelement by giving it a variable in the view such as
<ons-tabbar #myTabbar>and then declaring it as a
ViewChildin the component with
@ViewChild('myTabbar') tabbar;(as documented here).
The problem with the tabbar is that on the
ngAfterViewInit()hook the elements are not initialized yet because they are loaded asynchronously so you need to access the DOM to set the
activeattribute with something like
Let me know if it worked for you :+1:
@misterjunio Thanks! It works! :thumbsup: I thought that there is a way to invoke a method setActiveTab(index, [options]) https://onsen.io/v2/docs/angular2/ons-tabbar.html#method-setActiveTab
@Aleksandr-Pchelin You can invoke that for example after the press of a button or something, the problem here is that on init the tabbar component is not fully initialized yet (the tabs are loaded later). If you place say a
postchangelistener on the
ngAfterViewInit()hook that calls the
setActiveTabmethod you will see that it works. However of course you don’t want to do this on every change, only the beginning, that’s why you need that trick from my previous comment :smile:
philheslop last edited by
@misterjunio Hi, I am trying to do exactly this - change the tab after a button press, but i don’t see the setActiveTab function in the object returned by ViewChild (i.e. “tabbar”) - how would I get this function? (setting the tab to active as you suggest only works during initialisation, not on subsequent button presses…)