NativeScript handling back button event

krv picture krv · Nov 15, 2016 · Viewed 17.1k times · Source

I am trying to handle the hardware back button in a NativeScript app. I am using NativeScript version 2.3.0 with Angular.

Here is what I have in main.ts file

// this import should be first in order to load some required settings (like globals and reflect-metadata)
import { platformNativeScriptDynamic, NativeScriptModule } from "nativescript-angular/platform";
import { NgModule,Component,enableProdMode } from "@angular/core";
import { AppComponent } from "./app.component";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { routes, navigatableComponents } from "./app.routing";
import { secondComponent } from "./second.component";
import {AndroidApplication} from "application";
@Component({
    selector: 'page-navigation-test',
    template: `<page-router-outlet></page-router-outlet>`
})
export class PageNavigationApp {
}
@NgModule({
    declarations: [AppComponent,PageNavigationApp,secondComponent
        // ...navigatableComponents
        ],
    bootstrap: [PageNavigationApp],
    providers:[AndroidApplication],
    imports: [NativeScriptModule,
        NativeScriptRouterModule,
    NativeScriptRouterModule.forRoot(routes)
    ],
})
class AppComponentModule {

    constructor(private androidapplication:AndroidApplication){
        this.androidapplication.on("activityBackPressed",()=>{
            console.log("back pressed");

        })
    }

}

enableProdMode();

platformNativeScriptDynamic().bootstrapModule(AppComponentModule);

I am importing application with

import {AndroidApplication} from "application";

Then in the constrouctor of appComponentModule I am registering the event for activityBackPressed and just doing a console.log.

This does not work.

What am I missing here?

Answer

Eddy Verbruggen picture Eddy Verbruggen · Dec 22, 2016

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.