How to Create a PWA with Angular

Get step-by-step guidance on how to create a Progressive Web App with Angular and leverage its powerful features and benefits

Creating a Progressive Web App (PWA) with Angular offers a powerful way to combine the reach of the web with the performance and user experience of a native app. Angular, a popular framework for building web applications, provides robust support for PWA features, making it an excellent choice for developers looking to create high-performance, offline-capable web apps. This guide will walk you through the process of transforming an Angular application into a fully functional PWA, covering everything from setup to advanced features.

Setting Up Your Angular Project

Installing Angular CLI

The first step in creating an Angular PWA is to set up your development environment. Angular CLI (Command Line Interface) is a powerful tool that simplifies the process of creating and managing Angular projects. If you haven’t installed Angular CLI yet, you can do so by running the following command in your terminal:

npm install -g @angular/cli

This command installs Angular CLI globally on your system, allowing you to create new projects and manage existing ones with ease. Once the installation is complete, you can verify it by running:

ng version

This will display the installed version of Angular CLI, confirming that it is ready to use.

Creating a New Angular Project

With Angular CLI installed, you can create a new Angular project. Open your terminal and run the following command:

ng new my-pwa

This command will prompt you to choose some configuration options for your new project, such as whether to include Angular routing and which stylesheets format to use. Choose the options that best suit your project needs and Angular CLI will generate a new project with the specified configuration.

Once the project is created, navigate into the project directory:

cd my-pwa

You now have a basic Angular application set up and ready for development. The next step is to transform this application into a Progressive Web App.

To enable PWA features in your Angular application, you need to add the Angular PWA package.

Adding PWA Support to Your Angular App

Installing Angular PWA Package

To enable PWA features in your Angular application, you need to add the Angular PWA package. This package includes everything required to turn your Angular app into a PWA, including service worker support, a web app manifest, and more. To add the Angular PWA package, run the following command in your project directory:

ng add @angular/pwa

This command will automatically update your Angular project with PWA capabilities. It will add a service worker configuration, create a web app manifest, and include icons for your app. After running this command, your project will be configured with the necessary files and settings to support PWA features.

Configuring the Manifest File

The web app manifest is a JSON file that provides metadata about your app, such as its name, icons, theme colors, and start URL. The Angular PWA package generates a default manifest file, but you may need to customize it to match your app’s branding and requirements.

Open the src/manifest.webmanifest file in your project directory. You will see a JSON structure similar to the following:

{
"name": "My PWA",
"short_name": "PWA",
"theme_color": "#1976d2",
"background_color": "#fafafa",
"display": "standalone",
"scope": "/",
"start_url": "/",
"icons": [
{
"src": "assets/icons/icon-72x72.png",
"sizes": "72x72",
"type": "image/png"
},
{
"src": "assets/icons/icon-96x96.png",
"sizes": "96x96",
"type": "image/png"
},
{
"src": "assets/icons/icon-128x128.png",
"sizes": "128x128",
"type": "image/png"
},
{
"src": "assets/icons/icon-144x144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "assets/icons/icon-152x152.png",
"sizes": "152x152",
"type": "image/png"
},
{
"src": "assets/icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "assets/icons/icon-384x384.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "assets/icons/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}

Update the fields to reflect your app’s details. For example, you can change the name and short_name to match your app’s name, and update the icons with your own icon files. This customization ensures that your PWA has the correct branding and appears as intended when installed on users’ devices.

Implementing Service Workers

Understanding Service Workers

Service workers are a core component of PWAs, enabling offline functionality, caching, and background synchronization. They act as a proxy between the web application and the network, intercepting network requests and serving cached responses when the network is unavailable. This capability is crucial for providing a reliable and responsive user experience, even in areas with poor connectivity.

In an Angular PWA, the Angular Service Worker is configured to manage caching and handle network requests. The service worker is generated and managed by the Angular PWA package, making it easy to implement and customize.

Customizing Service Worker Configuration

The service worker configuration in an Angular PWA is defined in the ngsw-config.json file, located in the src directory. This file specifies the caching behavior for different types of resources, such as application shell files, data assets, and static content.

Open the ngsw-config.json file, and you will see a structure like this:

{
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/*.css",
"/*.js"
]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**",
"/*.png",
"/*.jpg"
]
}
}
]
}

The assetGroups array defines different groups of resources and their caching strategies. The app group includes the main application shell files, which are cached using the prefetch strategy to ensure they are available offline immediately after the initial load. The assets group includes additional static assets, which are cached using the lazy strategy to save bandwidth and storage.

You can customize these groups to include other resources or adjust the caching strategies to better suit your app’s needs. For example, if your app relies on frequently updated data from an API, you might want to add a data group with specific caching rules for API responses.

Testing and Debugging Your Angular PWA

Running the Application

Once you have configured your Angular PWA, it’s time to test it. Start by running your Angular application using the following command:

ng serve

This command starts a development server and hosts your application locally. Open your web browser and navigate to http://localhost:4200 to see your PWA in action. The development server provides live reloading, so any changes you make to the code will automatically refresh the browser.

Using Lighthouse for Audits

Google Lighthouse is a powerful tool for auditing and optimizing PWAs. It provides detailed reports on various aspects of your PWA, including performance, accessibility, best practices, SEO, and PWA features. Running a Lighthouse audit helps identify areas for improvement and ensures that your PWA meets industry standards.

To run a Lighthouse audit, follow these steps:

  1. Open your PWA in Google Chrome.
  2. Open DevTools by right-clicking on the page and selecting “Inspect” or pressing Ctrl+Shift+I.
  3. Go to the “Lighthouse” tab.
  4. Select the categories you want to audit (Performance, Accessibility, Best Practices, SEO, PWA).
  5. Click “Generate report.”

Lighthouse will analyze your PWA and provide a detailed report with scores and recommendations. Use this feedback to address any issues and optimize your PWA for a better user experience.

Advanced PWA Features

Push Notifications

Push notifications are a powerful way to engage users and keep them informed about updates, promotions, and other relevant content. Implementing push notifications in an Angular PWA involves using the Angular Service Worker and the Push API.

First, you need to request permission from the user to send notifications. Add the following code to your main component:

import { SwPush } from '@angular/service-worker';

constructor(private swPush: SwPush) {}

requestSubscription() {
this.swPush.requestSubscription({
serverPublicKey: 'YOUR_PUBLIC_VAPID_KEY'
})
.then(sub => {
// Send the subscription object to the server
console.log('Subscription object: ', sub);
})
.catch(err => {
console.error('Could not subscribe to notifications', err);
});
}

Next, handle push events in your service worker. Open the src/service-worker.js file and add the following code:

self.addEventListener('push', event => {
const data = event.data.json();
console.log('Push received:', data);

const options = {
body: data.body,
icon: 'assets/icons/icon-192x192.png',
badge: 'assets/icons/badge-72x72.png'
};

event.waitUntil(
self.registration.showNotification(data.title, options)
);
});

By implementing push notifications, you can enhance user engagement and keep users informed about important updates and events.

Background Sync allows your PWA to defer tasks until the user has a stable network connection.

Background Sync

Background Sync allows your PWA to defer tasks until the user has a stable network connection. This feature is useful for scenarios where users may perform actions offline that need to be synchronized once the connection is restored.

To implement Background Sync in an Angular PWA, register a sync event in your service worker:

self.addEventListener('sync', event => {
if (event.tag === 'sync-tag') {
event.waitUntil(syncData());
}
});

function syncData() {
// Logic to synchronize data with the server
return fetch('/sync-endpoint', {
method: 'POST',
body: JSON.stringify({ data: 'user-data' }),
headers: {
'Content-Type': 'application/json'
}
});
}

In your main component, register the sync event:

navigator.serviceWorker.ready.then(registration => {
return registration.sync.register('sync-tag');
});

Using Background Sync ensures that your app can handle offline interactions smoothly and synchronize data when the network is available, providing a seamless user experience.

Optimizing Your Angular PWA

Improving Performance with Lazy Loading

Lazy loading is a technique used to optimize the performance of your Angular PWA by loading only the necessary modules and components when they are needed. This reduces the initial load time and improves the overall user experience, especially on slower networks.

To implement lazy loading in your Angular application, you need to configure your routing module. Here’s how you can set up lazy loading for a feature module:

  1. Create a Feature Module:
ng generate module feature --route feature --module app.module

This command creates a new feature module and sets up lazy loading for it. The --route option specifies the route path, and --module specifies the parent module where the routing configuration is applied.

  1. Configure Lazy Loading in the App Routing Module:

Open the src/app/app-routing.module.ts file and configure the routes:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', loadChildren: () => import('./home/home.module').then(m => m.HomeModule) },
{ path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) },
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

In this configuration, the loadChildren property is used to lazy load the feature module only when the user navigates to the feature route.

  1. Create Feature Components:

Generate components within the feature module:

ng generate component feature/feature-component

By lazy loading feature modules and their components, you can significantly improve the initial load time of your Angular PWA, providing a faster and smoother experience for users.

Utilizing Web Workers for Parallel Processing

Web workers allow you to run scripts in background threads, enabling you to perform computationally expensive tasks without blocking the main thread. This can enhance the performance of your Angular PWA by offloading heavy processing tasks to web workers.

To use web workers in your Angular application, follow these steps:

  1. Generate a Web Worker:
ng generate web-worker src/app/worker

This command creates a new web worker file in your project. The generated src/app/worker.worker.ts file contains the initial setup for the worker.

  1. Implement the Worker Logic:

Open the worker.worker.ts file and add the logic for your background task:

/// <reference lib="webworker" />

addEventListener('message', ({ data }) => {
const response = `Worker response to ${data}`;
postMessage(response);
});
  1. Communicate with the Worker from Your Component:

In your component, create an instance of the worker and handle messages:

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
worker: Worker;

constructor() {
if (typeof Worker !== 'undefined') {
this.worker = new Worker(new URL('./worker.worker', import.meta.url));
this.worker.onmessage = ({ data }) => {
console.log(`Received message from worker: ${data}`);
};
} else {
console.log('Web Workers are not supported in this environment.');
}
}

sendMessageToWorker() {
if (this.worker) {
this.worker.postMessage('Hello, worker');
}
}
}

By using web workers, you can enhance the performance of your Angular PWA, ensuring that heavy processing tasks do not interfere with the main thread and user interactions.

Deploying Your Angular PWA

Building for Production

To deploy your Angular PWA, you need to build the project for production. The production build optimizes the application for performance and creates a set of static files that can be served by a web server. Run the following command to build your Angular PWA:

ng build --prod

This command generates the production-ready files in the dist/ directory. The build process includes optimizations such as minification, ahead-of-time (AOT) compilation, and tree-shaking to reduce the bundle size and improve performance.

Deploying to a Web Server

After building your Angular PWA for production, the next step is to deploy the static files to a web server. There are various hosting options available, including traditional web servers (like Apache or Nginx), cloud services (like Firebase Hosting or AWS S3), and static site hosts (like Netlify or Vercel).

Here’s an example of deploying an Angular PWA to Firebase Hosting:

  1. Install Firebase CLI:
npm install -g firebase-tools
  1. Initialize Firebase in Your Project:
firebase init

During the initialization process, select “Hosting” and choose your project. Configure the public directory as dist/your-project-name, and set up the project for single-page application (SPA) by answering “Yes” to the rewrite all URLs to index.html question.

  1. Deploy to Firebase Hosting:
firebase deploy

This command deploys your Angular PWA to Firebase Hosting. You will receive a URL where your app is hosted and accessible to users.

By following these steps, you can successfully deploy your Angular PWA, making it available to users across the globe.

Real-World Examples of Angular PWAs

Google I/O PWA

The Google I/O PWA is a prime example of an Angular PWA that provides a rich, interactive experience for event attendees. The app offers offline access to schedules, speaker information, and conference details, ensuring that users can access critical information even without an internet connection.

The Google I/O PWA leverages Angular’s powerful features and the PWA capabilities to deliver a seamless user experience. Features like push notifications keep attendees informed about schedule changes and important announcements, enhancing engagement and usability.

Medium PWA

Medium, a popular online publishing platform, uses an Angular PWA to enhance its user experience. The Medium PWA offers fast loading times, offline access to articles, and an app-like interface. By leveraging Angular’s robust framework and PWA features, Medium provides a high-performance reading experience that keeps users engaged and coming back for more.

The Medium PWA showcases the potential of Angular PWAs in delivering content-rich applications with excellent performance and usability. The app’s ability to function offline ensures that readers can access their favorite articles anytime, anywhere.

Conclusion

Creating a Progressive Web App (PWA) with Angular involves several steps, from setting up your development environment and configuring the manifest file to implementing service workers and advanced features like push notifications and Background Sync. By following the guidelines outlined in this article, you can transform your Angular application into a fully functional PWA that offers an app-like experience, improved performance, and offline capabilities.

PWAs are a powerful tool in modern web development, providing numerous benefits such as enhanced user engagement, broader reach, and cost efficiency. By leveraging Angular’s robust support for PWA features, you can create high-quality, responsive web applications that meet the demands of today’s users.

If you have any questions or need further assistance with creating a PWA with Angular, feel free to reach out. Thank you for reading, and best of luck with your Progressive Web App development journey!

Read Next: