Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save guillaumegarcia13/64eb3098428972b7cd444b519c3e859e to your computer and use it in GitHub Desktop.
Save guillaumegarcia13/64eb3098428972b7cd444b519c3e859e to your computer and use it in GitHub Desktop.
Angular - Add to home screen POC (app.component.ts)
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'app-root',
template: '<button (click)="addToHomeScreen()" *ngIf="showButton">Add to Home Scree</button>',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
deferredPrompt: any;
showButton = false;
@HostListener('window:beforeinstallprompt', ['$event'])
onbeforeinstallprompt(e) {
console.log(e);
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
this.deferredPrompt = e;
this.showButton = true;
}
addToHomeScreen() {
// hide our user interface that shows our A2HS button
this.showButton = false;
// Show the prompt
this.deferredPrompt.prompt();
// Wait for the user to respond to the prompt
this.deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
this.deferredPrompt = null;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment