0

I designed an element on the main page of my app that, when clicked, changes the active tab.

I used to do the following:

events.subscribe('change-tab', (tab, filterOnSport) => {
      console.log('TabsPage#constructor - change-tab event received with params: ', tab, filterOnSport);
      if (filterOnSport) this.findTabParams.filterOnSport = filterOnSport;
      this.tabs.select(tab);
    });

But this doesn't work the first time around, if the said tab has never been visited (see https://github.com/ionic-team/ionic/issues/12592)

I saw in the Github issue that someone suggested to simulate a click on the tab.

I am trying to use ViewChildto do so but can't manage to make it work.

// View
<ion-tabs #tabs>
  <ion-tab [root]="tab1Root" tabIcon="home"></ion-tab>
  <ion-tab #findTab [root]="tab2Root" [rootParams]="findTabParams" tabIcon="search"></ion-tab>
  <ion-tab [root]="tab3Root" tabIcon="chatbubbles" [tabBadge]="unread?1:null" [tabsHideOnSubPages]=true></ion-tab>
  <!--<ion-tab [root]="tab3Root" tabIcon="chatbubbles" [tabBadge]="totalUnreadMessages?.$value" [tabsHideOnSubPages]=true></ion-tab>-->
</ion-tabs>

// Controller
@ViewChild('findTab') findTab: ElementRef;
...
ngAfterViewInit() {
    console.log('TAB elem ', this.findTab);
    // How click the tab ?
  }

How could I trigger the click function of the tab?

Manuel RODRIGUEZ
  • 2,131
  • 3
  • 25
  • 53
  • a wild guess is : `this.findTab.nativeElement.click();` Another way to find out is to use the devtool in you browser, break you code at the console.log and play around with the findTab element in your console till you find a solution – kodeaben Sep 26 '17 at 10:37

2 Answers2

0

Take a look at this plunkr: https://plnkr.co/edit/KBWa5YbFCYYVQI97ACRQ?p=preview

//our root app component
import {Component, NgModule, VERSION, ViewChild} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <button #btn (click)="testClick()">hello</button>
    </div>
  `,
})
export class App implements AfterViewInit {
  @ViewChild('btn') myBtn; 
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  testClick(){
    window.alert("i have been clicked!")
  }

  ngAfterViewInit(){
    this.myBtn.nativeElement.click();
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
kodeaben
  • 1,829
  • 3
  • 24
  • 33
0

I decided to go this way as I have been recommended on GitHub :

document.getElementById(tabid).click();
Manuel RODRIGUEZ
  • 2,131
  • 3
  • 25
  • 53