How to restrict specific tabs to login when user tries to access it?

Hi,
I’m building a tabs app which has some restricted tabs on it, but I have no clue on how to implement login restriction when user tries to access the restricted tabs.

My initial thought is to show a login modal when the user tries to access the restricted tab and hasn’t logged in previously. Also, if the user refuses to login the navigation should be prevented.

I’ve read in the docs that there’s the ionChange output event but I couldn’t find a way to prevent it of navigating.

tabs.hml

<ion-tabs (ionChange)="onTabsChange($tab)">    
  <ion-tab [root]="tab1Root" tabTitle="Home"></ion-tab> 
  <ion-tab [root]="tab2Root" tabTitle="News"></ion-tab> 
  <ion-tab [root]="tab3Root" tabTitle="Restricted"></ion-tab>
</ion-tabs>

tabs.ts

import { Component } from '@angular/core';


import { HomePage } from '../home/home';
import { NewsPage } from '../news/news';
import { RestrictedPage } from '../restricted/restricted';

@Component({
  selector: 'main-tabs', 
  templateUrl: 'tabs.html'
})
export class TabsPage { 
  tab1Root: any = HomePage; 
  tab2Root: any = NewsPage; 
  tab3Root: any = RestrictedPage; 

  constructor(navParams: NavParams) {

  }

  onTabsChange($tab){
    console.log($tab);
  }
}

Does anyone know how can I do this?
Or maybe, Is there a more appropriate way of doing this?

I think you should prevent the tabs from showing completely if not logged in, anyhow here’s an event you can put in the components for the tabs:

ionViewCanEnter(): boolean | Promise<void> {
    // logic
}

https://ionicframework.com/docs/api/navigation/NavController/ Go to lifecycle events

If you make login manually triggered, you can bind the [enabled] property of the restricted tab to reflect whether or not the user is logged in.

2 Likes