Angular Universal Setup 🎯

beginner
13 min

Angular Universal Setup 🎯

Welcome to our comprehensive guide on setting up Angular Universal! In this tutorial, we'll walk you through the process of creating a Universal Angular application, explaining why we use it, and providing real-world examples. Let's get started!

What is Angular Universal? 📝

Angular Universal is a feature that allows Angular applications to render on the server-side, generating a fully-hydrated HTML page that can be sent to the client, improving performance and SEO.

Setting Up Angular Universal 💡

To set up Angular Universal, you'll need to have Node.js, npm, and Angular CLI installed. If you haven't already, follow these steps to install them:

  1. Install Node.js
  2. Install npm
  3. Install Angular CLI

Once you have those tools installed, follow these steps to create an Angular Universal application:

bash
ng new my-universal-app --style=scss --routing --navigation cd my-universal-app ng add @nguniversal/express-engine

Let's break down this command:

  • ng new: Creates a new Angular application
  • --style=scss: Sets the styles to SCSS
  • --routing: Includes Angular Router
  • --navigation: Includes Angular Material for navigation
  • cd: Changes the current directory
  • ng add: Adds a package to your Angular application
  • @nguniversal/express-engine: Adds Angular Universal and sets up a simple Express server

Running the Application ✅

Now that you've set up Angular Universal, you can run the application using the following commands:

  1. Develop (client-side only): ng serve
  2. Server-side rendering and development (both client and server): npm run dev:ssr
  3. Build (client-side only): ng build
  4. Build and server-side render (both client and server): npm run build:ssr
Quick Quiz
Question 1 of 1

What command runs the application with server-side rendering and development?

Code Examples 💡

Let's take a look at two complete, working examples of server-side rendering in Angular Universal.

Example 1: Server-side rendering the homepage

typescript
// app/src/main.server.ts import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; if (process.env.NODE_ENV === 'production') { enableProdMode(); } export function main() { return platformBrowserDynamic().bootstrapModule(AppModule).then(ref => { // The ref.component is the AppComponent instance const app = ref.component.instance; // The AppComponent's ngOnInit method has already been called at this point // Index is the main route for our application const url = '/'; // Set the URL and tell Angular to generate the HTML app.serverUrl = url; app.generateServerResponse(); }); }

Example 2: Sharing data between client and server

typescript
// app/src/app/app.component.ts import { Component } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent { // Set the server URL when the route changes constructor(private route: ActivatedRoute) { this.route.url.subscribe((segments) => { this.serverUrl = '/' + segments[0].path; }); } // The server URL to render the HTML for serverUrl = '/'; // Generates the server response generateServerResponse() { // This function is called on the server-side when generating the HTML // You can perform any server-side logic here and pass it as a context // to your template const context = { welcomeMessage: 'Hello from the server!', }; // Call the app's server-side rendering method and pass the context this.appServer.generate(context).subscribe((response) => { // The response is the server-rendered HTML // You can use it to update the DOM, set it as the document's HTML, etc. }); } }

Conclusion 🎯

In this tutorial, we've walked through setting up an Angular Universal application, explained why we use it, and provided two complete, working examples. With this knowledge, you're well on your way to creating high-performance, SEO-friendly Angular applications!

Keep learning, keep coding, and happy crafting! 🚀