Introduction
Angular Universal is a technology that allows you to perform server-side rendering (SSR) of your Angular applications. This means that instead of rendering your application entirely in the browser, parts of it can be rendered on the server and then sent to the client. This can significantly improve the performance and SEO of your application.
Key Benefits of Angular Universal:
- Improved Performance: Faster initial load times as the server sends a fully rendered page to the client.
- Better SEO: Search engines can crawl the fully rendered HTML, improving the discoverability of your application.
- Enhanced User Experience: Users see content faster, leading to a better overall experience.
Setting Up Angular Universal
Step 1: Install Angular Universal
First, you need to add Angular Universal to your existing Angular project. You can do this using the Angular CLI.
This command will:
- Install the necessary packages.
- Create a server-side app module.
- Update your
angular.json
file to include server-side rendering configurations.
Step 2: Update Server Module
The ng add
command will create a server.ts
file and a main.server.ts
file. These files are used to bootstrap your Angular application on the server.
server.ts
import 'zone.js/dist/zone-node'; import { ngExpressEngine } from '@nguniversal/express-engine'; import * as express from 'express'; import { join } from 'path'; import { AppServerModule } from './src/main.server'; import { APP_BASE_HREF } from '@angular/common'; import { existsSync } from 'fs'; const app = express(); const PORT = process.env.PORT || 4000; const DIST_FOLDER = join(process.cwd(), 'dist/browser'); // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine) app.engine('html', ngExpressEngine({ bootstrap: AppServerModule, })); app.set('view engine', 'html'); app.set('views', DIST_FOLDER); // Example Express Rest API endpoints // app.get('/api/**', (req, res) => { }); // Server static files from /browser app.get('*.*', express.static(DIST_FOLDER, { maxAge: '1y' })); // All regular routes use the Universal engine app.get('*', (req, res) => { res.render('index', { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] }); }); // Start up the Node server app.listen(PORT, () => { console.log(`Node Express server listening on http://localhost:${PORT}`); });
Step 3: Build and Serve
To build your application for server-side rendering, you need to run the following command:
This will create a dist
folder with two subfolders: browser
and server
.
To serve your application, run:
This will start an Express server that serves your Angular application with server-side rendering.
Practical Example
Let's create a simple example to demonstrate how Angular Universal works.
Step 1: Create a New Component
Create a new component called server-info
.
Step 2: Update the Component
Update the server-info.component.ts
file to display some server-side information.
import { Component, OnInit } from '@angular/core'; import { isPlatformServer } from '@angular/common'; import { PLATFORM_ID, Inject } from '@angular/core'; @Component({ selector: 'app-server-info', templateUrl: './server-info.component.html', styleUrls: ['./server-info.component.css'] }) export class ServerInfoComponent implements OnInit { isServer: boolean; constructor(@Inject(PLATFORM_ID) private platformId: Object) { } ngOnInit(): void { this.isServer = isPlatformServer(this.platformId); } }
Update the server-info.component.html
file to display whether the component is being rendered on the server or the client.
<div> <p *ngIf="isServer">This content is rendered on the server.</p> <p *ngIf="!isServer">This content is rendered on the client.</p> </div>
Step 3: Add the Component to App Module
Add the ServerInfoComponent
to your AppModule
.
import { ServerInfoComponent } from './server-info/server-info.component'; @NgModule({ declarations: [ // other components ServerInfoComponent ], // other configurations }) export class AppModule { }
Step 4: Use the Component in Your Application
Add the ServerInfoComponent
to your app.component.html
.
Step 5: Build and Serve
Build and serve your application again using the following commands:
Visit http://localhost:4000
to see your application with server-side rendering.
Conclusion
In this section, you learned about Angular Universal and how to set it up in your Angular application. You also created a simple example to demonstrate server-side rendering. By using Angular Universal, you can significantly improve the performance and SEO of your Angular applications, providing a better user experience.
Next, we will dive into performance optimization techniques to further enhance your Angular applications.
Angular Course
Module 1: Introduction to Angular
- What is Angular?
- Setting Up the Development Environment
- Angular Architecture
- First Angular Application
Module 2: Angular Components
- Understanding Components
- Creating Components
- Component Templates
- Component Styles
- Component Interaction
Module 3: Data Binding and Directives
- Interpolation and Property Binding
- Event Binding
- Two-Way Data Binding
- Built-in Directives
- Custom Directives
Module 4: Services and Dependency Injection
Module 5: Routing and Navigation
Module 6: Forms in Angular
Module 7: HTTP Client and Observables
- Introduction to HTTP Client
- Making HTTP Requests
- Handling HTTP Responses
- Using Observables
- Error Handling
Module 8: State Management
- Introduction to State Management
- Using Services for State Management
- NgRx Store
- NgRx Effects
- NgRx Entity
Module 9: Testing in Angular
Module 10: Advanced Angular Concepts
- Angular Universal
- Performance Optimization
- Internationalization (i18n)
- Custom Pipes
- Angular Animations