Onkar Nene Onkar Nene - 5 months ago 290
Android Question

NativeScript + angular 2 : Use of back button click listener

I am developing cross platform mobile application using NativeScript + Angular 2.

I want to handle back button click of the current View, i.e. when user clicks on back button in android device, i want to perform an action like killing / removing the current view from the stack.

For ex: In android platform (Native Development) we can use

finish()
method of the activity for removing it from the stack. We can handle onBackPressed() like -

@Override
public void onBackPressed()
{
finish(); //Removes current Activity from stack
}


So is there any way to handle
onBackPressed()
and
finish()
method in NativeScript + angular 2? I googled a lot but didn't find any solution and also tried
Frame.goBack()
in NativeScript + Angular 2, but didn't worked for me. It works great in NativeScript + JavaScript.

Answer

What you need to implement going back is to inject Location and use the method back()

import {Location} from '@angular/common';

@Component({ ... })
export class MyComponent {
    constructor(private location: Location) { }

    public goBack() {
        this.location.back();
    }
}

At this point when the user goes back, you shouldn't worry about explicitly destroying the view as there is no mobile option for going "forward"