Reputation: 384
I am using angular 7 and ionic 5. When i want to redirect to previous page using hardware back button, ionic app is closing itself. I am using below code but its not working.
this.platform.backButton.subscribeWithPriority(9999, () => {
document.addEventListener('backbutton', function (event) {
event.preventDefault();
event.stopPropagation();
console.log('hello');
}, false);
});
Upvotes: 3
Views: 3396
Reputation: 3606
If you are using ionic with Capacitor you need to use this code in the constructor of app.component.ts:
import { App } from '@capacitor/app';
import { Location } from '@angular/common';
constructor(private _location: Location)
{
App.addListener('backButton', () =>
{
if (this._location.isCurrentPathEqualTo('/home'))
{
navigator['app'].exitApp();
}
else
{
this._location.back();
}
});
}
Upvotes: 2
Reputation: 1100
Try this,
this.platform.backButton.subscribeWithPriority(10, () => {
this.router.navigate(['']); // route to previous page or component
});
Upvotes: 0
Reputation: 299
I use the directive for this
import { Directive, HostListener } from '@angular/core';
import { PlatformService } from 'src/app/services/platform';
@Directive({
selector: '[disableBackButton]'
})
export class DisableBackButtonDirective {
constructor(
private platformService: PlatformService
) { }
@HostListener('document:ionBackButton', ['$event'])
overrideHardwareBackAction(event: any) {
if (this.platformService.isPlatform('android')) {
event.detail.register(100, async () => {
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
});
}
}
}
in page.html
<ion-content disableBackButton>
....
</ion-content>
in page.ts
this.platform.backButton.subscribe(() => {
console.log('hello');
});
Upvotes: 0