Skip to content

Instantly share code, notes, and snippets.

@pnutmath
Last active March 12, 2021 20:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pnutmath/a50521057bacd559e6fe34173641c4b0 to your computer and use it in GitHub Desktop.
Save pnutmath/a50521057bacd559e6fe34173641c4b0 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