How to block navigation to other tab if form isn't valid

605 views Asked by At

I have an ionic2 tabs based application. On one tab I have a form. I want the app to block when I switch to another tab, and the form isn't valid.

In ng2 I could use a routeGuard for these sorts of scenarios, but is there a solution for this scenario in ionic2?

From other posts I understand that ionic2 doesn't work with routing, the way Angular 2 does.

Can anyone give me a hint?

2

There are 2 answers

1
Dharmik Patel On

You can consider to use ngOnInit() Method. For ex- Here you dont load dashboard if user does not have auth key. you redirect user back to other component i.e /login in this case.

import { Component, OnInit} from '@angular/core';
declare var User:any;

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css'],
  providers: [ResultService]

})



export class DashboardComponent implements OnInit {
 username: string;

 constructor(private router: Router, private resultService: ResultService) {

 }

 ngOnInit() {

  if(!User.hasAuthKey()){
    this.router.navigate(['login']);
  }else{
    var usr = User.checkAuthorized();
    this.username = usr.firstname;
  }

}
1
Doek On

I found exactly what I was looking for in the ionic v2docs: NavController

Turns out you can use the IonViewCanLeave hook For this in the page you are leaving.

Nav Guards: In some cases, a developer should be able to control views leaving and entering. To allow for this, NavController has the ionViewCanEnter and ionViewCanLeave methods. Similar to Angular 2 route guards, but are more integrated with NavController. For example, if you wanted to prevent a user from leaving a view

Start Reading from the above passage in the article for an example