Search code examples
angularionic-frameworkobservableproperty-binding

Property binding not detecting change within observable


The selectedIndex attribute is bound to the index property. The view is not updated when index property is changed within the AngularFireAuth observable as shown below. Why not? It works fine anywhere outside the observable. The .ts and .html files are shown below.

Here is the html file

<ion-tabs [selectedIndex]="index">
    <ion-tab [root]="t0" tabTitle =" My Account" tabIcon="body"></ion-tab>    
    <ion-tab [root]="t1" tabTitle ="Sections" tabIcon="home"></ion-tab>
</ion-tabs>

Here is the .ts file

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase'

@IonicPage()
@Component({
  selector: 'page-tabs',
  templateUrl: 'tabs.html',
})
export class TabsPage {
  index = 0;
  t0 = "AccountPage";
  t1 = "HomePage";

  constructor(public navCtrl: NavController, public navParams: NavParams, public afAuth: AngularFireAuth) {

    afAuth.authState.subscribe((fbuser: firebase.User) => {
      if (!fbuser) {
        this.index = 0;
        console.log(this.index)
      }
      else {
        this.index = 1;
        console.log(this.index)
      }
    });
// setting the index outside the observable works normally
  }

  ionViewDidLoad() {
  }

}

Solution

  • EDIT :I will use this work around for now. Manually setting the selectedIndex attribute.

    import { Component, ViewChild } from '@angular/core';
    import { IonicPage, NavController, NavParams } from 'ionic-angular';
    import { AngularFireAuth } from 'angularfire2/auth';
    import * as firebase from 'firebase'
    import { Tabs } from 'ionic-angular/navigation/nav-interfaces';
    
    @IonicPage()
    @Component({
      selector: 'page-tabs',
      templateUrl: 'tabs.html',
    
    })
    export class TabsPage  {
      @ViewChild('myTabs') tabRef: Tabs;
    
      t0 = "AccountPage";
      t1 = "HomePage";
      fbuser2: firebase.User;
    
      constructor(public navCtrl: NavController, public navParams: NavParams,
        public afAuth: AngularFireAuth) {
    
        this.afAuth.authState.subscribe((fbuser: firebase.User) => {
          if (!fbuser) {
            this.setIndex(0);
          }
          else {
            this.setIndex(1);        
          }
        });
    
      }
      setIndex(i: number) { 
        this.tabRef.select(i);
       }
    
    
    }