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.


  • Onsen UI

    @Aleksandr-Pchelin Can’t you just set the active attribute on the tab you wish to load as default?



  • @misterjunio Hi! I want set active tab with value of query string parameter.


  • Onsen UI

    @Aleksandr-Pchelin I was able to find a solution. You can access the tabbar element by giving it a variable in the view such as <ons-tabbar #myTabbar> and then declaring it as a ViewChild in 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 active attribute with something like this.tabbar.nativeElement.querySelectorAll('ons-tab')[1].setAttribute('active', true).

    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


  • Onsen UI

    @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 postchange listener on the ngAfterViewInit() hook that calls the setActiveTab method 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:


Log in to reply