NativeScript handling back button event

I'm using NativeScript with Angular as well and this seems to work quite nicely for me:

import { RouterExtensions } from "nativescript-angular";
import * as application from "tns-core-modules/application";
import { AndroidApplication, AndroidActivityBackPressedEventData } from "tns-core-modules/application";

export class HomeComponent implements OnInit {
  constructor(private router: Router) {}
    
  ngOnInit() {
    if (application.android) {
      application.android.on(AndroidApplication.activityBackPressedEvent, (data: AndroidActivityBackPressedEventData) => {
        if (this.router.isActive("/articles", false)) {
          data.cancel = true; // prevents default back button behavior
          this.logout();
        }
      });
    }
  }
}

Note that hooking into the backPressedEvent is a global thingy so you'll need to check the page you're on and act accordingly, per the example above.


import { Component, OnInit } from "@angular/core";
import * as Toast from 'nativescript-toast';
import { Router } from "@angular/router";
import * as application from 'application';

@Component({
  moduleId: module.id,
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})
export class MainComponent {
  tries: number = 0;
  constructor(
    private router: Router
  ) {
    if (application.android) {
      application.android.on(application.AndroidApplication.activityBackPressedEvent, (args: any) => {
        if (this.router.url == '/main') {
          args.cancel = (this.tries++ > 0) ? false : true;
          if (args.cancel) Toast.makeText("Press again to exit", "long").show();
          setTimeout(() => {
            this.tries = 0;
          }, 2000);
        }
      });
    }
  }
}