×

Angular 8 universal

Angular 8 universal

Angular Universal is a technology that allows server-side rendering for Angular apps. An angular app is a single-page app, and it runs in a client-side browser. Rendering pages in the DOM is a response to the user reaction. 

Angular Universal executes in the server, generating static application pages that get bootstrapped on the client. This means that the application renders more quickly, giving users a chance to view the application layout before it becomes fully interactive.

Angular 8 universal

We can easily prepare an app for server-side rendering using the Angular CLI. The CLI scematic @nguniversal/ express-engine performs the required steps, as described below.

Universal tutorial

The Tour of Heroes tutorial is the foundation for this walkthrough. In this example, the app with the Ahead-of-Time (AoT) compiler. A Node Express web server compiles HTML pages with Universal based on clients requests.

To create the server-side app module, app.server.module.ts, run the following CLI command.

ng add @nguniversal/express-engine --clientProject angular.io-example

The command creates the following folder structure.

src/index.html                    app web page
   main.ts                         bootstrapper for client app
   main.server.ts             * bootstrapper for server app
   style.css                       styles for the app
   app/ ...                         application code
     app.server.module.ts     * server-side application module
 server.ts                               * express web server 
 tsconfig.json                    TypeScript client configuration
 tsconfig.app.json            TypeScript client configuration
 tsconfig.server.json         * TypeScript server configuration
 tsconfig.spec.json            TypeScript spec configuration
 package.json                     npm configuration
 webpack.server.config.js     * webpack server configuration 

The files marked with * are new and not in the original tutorial sample.

Universal in Action

To start rendering our app with universal on our local system, use the following command.

npm run builds:ssr && npm serve:ssr

open the browser and transform it to http://localhost:4000/. We can get familiar with the Tour of Heroes dashboard page.

Navigation via routerLinks works correctly because they use the native anchor (<a>) tags. We can go from the Dashboard to the Dashboard to the Heroes page and back. We can click a hero on the Dashboard page to display its Details page.

We can simulate a slower network to see the translation more clearly as follows:

  1. Open the chrome Dev Tools and go to the Network tab.
  2. Find the Network Throtting dropdown on the far right of the menu bar.
  3. Try one of the “3G” speeds.

Why we use server-side rendering?

There are mainly three main reasons to create a Universal version of our app.

  • Facilitate web crawlers by search engine optimization (SEO)
  • Improve performance on mobile and the low-powered devices.
  • Show the first page with a first-contentful paint (FCP)

Universal web servers

A universal web server receives to application page requests within static HTML redered by the universal template engine. The server responds to HTTP requests from the clients (like browsers), and server static assets such as scripts, CSS, and images.

Universal applications use the Angular platform-server package, which provides server implementations of the DOM, XMLHttpRequest, and other low-level features.

The renderModuleFactory() function takes as inputs in a template HTML page (usually index.html), an Angular module containing components, and a route that determines which components we have to display. The route comes from the client request to the server.

Each request results in the appropriate view for the requested route. The renderModuleFactory() function renders the view within the <app> tag of the template, creating a finished HTML page for the client.

Step 1: Add Angular Universal

First, we have to add universal angular support to our angular application for that we will run one cmd.

ng add @nguniversal/express-engine –clientProject<project name>
Add Angular Universal

Once it is done, we will see numerous changes in our project to know more about this transition visit Angular universal official

Step 2: Make changes in server.ts

Next step is to make changes in our server.ts

  1. We need to add export in front of app variable
Make changes in server.ts
  • We need to comment on the listening of our app, which is typically at the end of server.ts file.
comment on the listening of our app

Step 3: Export our app as a library

Now we need to export our app as a library with a library target as umd in web pack configuration typically its name is webpack.server.config.js

library target as umd in web pack configuration

Step 4: Initialize and configure firebase

In this level, we first need to install firebase tools in our system.

first need to install firebase tools

Then, we need to login into firebase from our cli

And then, we will initialize  a firebase hosting in our project

Npm g firebase-tools
Once the above cmd succeeds
firebase login
firebase init 
firebase
a firebase hosting
we have firebase in our angular project

Once, we have firebase in our angular project, and we need to make some changes in our firebase.json file.

we need to make some changes in our firebase.json file

We have to change the rewrite property in it.

change the rewrite property

“function”:”angularUniversalFunction”

Step 5: Build our project

npm run build:ssr

the above cmd has generated a dist folder which has three things in it a browser folder and serve.js file in our system.

browser folder and serve.js file in our system

Step 6: Automate the build folder movement

We need to copy the build folder form the root project to the functions folder for the  Smartcodehub.

npm i --save fs-extra

after the cmd, we will create one file and name it movedist.js, and the content will be

const fs = require('fs-extra');
(
    async()=>{
        const src = './dist';
        const dist = './functions/dist';await fs.remove(dist);
        await fs.copy(src,dist);
    }
)()

The above function will copy the dist from the root and paste it into functions folder.

Step 7: configure our primary firebase function

In thisa step, we need to set up our primary firebase function which is in the functions folder src directory and the filename is index.ts.

import * as functions from 'firebase-functions';const universal  = require(`${process.cwd()}/dist/server`).app;export const angularUniversalFunction = functions.https.onRequest(universal);

Step 8: deploy the firebase function

Rebuild our project

Npm run build: ssr

Node movedist.js

cd functions

Firebase deploy

deploy the firebase function

SPAs have many advantages above old traditional apps like:

  • The client is the responsibility of doing the most rendering. For the server, its primary role is serving the app files into the client.
  • No page refresh
  • No need for reaching the server for every action.
  • Easy navigation between different pages.
  • Improved performance.
  • No special request of the server to load new pages.
  • User-friendliness etc.

We call Universal apps, which SPAs with server-side rendering.


Related Topics

Difference between Angular and React

Difference between Angular and React Parameters AngularReactType Angular is a complete framework. React is a JavaScript library, and much older compared...

2 minutes read.

History and Versions of Angular 8

Introduction to Angular JS Misko created Angular JS and the first version of Angular also name as "Angular 1". He built a framework to handle the downfalls of HTML. The first...

3 minutes read.

Advantages | Disadvantages of Angular 8

Advantages of Angular 8 There are some Advantages of angular 8 which are given below: It offers clean code developmentHigher PerformanceAn angular framework can take care of routing, which...

1 minute read.

Angular 8 Architecture

Architecture of Angular 8 Angular 8 is a platform and framework which is used to create clients applications in HTML and Typescript. Angular 8 is written in Typescript. Typescript is a...

5 minutes read.

Node.js async.queue() Method

Node.js async.queue() Method What is Async module? In Node.js, we have an async module that has a lot of functionality, but the main use case of this module is to do multiple...

3 minutes read.

Angular 8 changes and new features

The angular version number indicates the level of changes introduced by the release. The use of semantic versioning helps us understand the potential impact of updating to a new version. Angular is the...

5 minutes read.

Dependency Injection in Angular 8

Dependency injection (DI), is an essential application design pattern. Angular 8 has its own DI framework, which used in the design of Angular application to increase efficiency and portability. Dependencies are the services that...

7 minutes read.

Angular 8 Error Fixing

We can get errors in Angular because of many causes. Let's see an example to see some specific types of errors. We have to create an app with the name "testing-app." In this app,...

4 minutes read.

Installation of Angular 8

Installation Guides to Angular 8 step by Step Angular combines declarative templates, dependency injection and, end to end tooling to solve development challenges. Angular empowers developers to build an application that lives on the...

4 minutes read.

ngSwitch Directive in Angular 8

Angular 8 ng-Switch Directive The ng-Switch Directive hides and shows the HTML elements depending on an expression. Child elements with the ng-switch-when directive will be displayed if it gets a match; otherwise, the component and...

2 minutes read.

Angular CLI Commands

All CLI commands of Angular Angular CLI is a command-line interface which is used to initialize, develop, and maintain Angular applications. We can use these Command on command prompt or consequentially by an associated...

8 minutes read.

Angular 8 Forms

Angular forms are used to handle the user's input. We use Angular form in our application to authorize users to log in, to update profile, to enter information, and to perform many other...

3 minutes read.

Express.js app.get() Request Function

Express.js Express is a flexible online application framework for Node.js that offers a strong set of functionality for both web and mobile applications. While preserving the familiar and adored Node.js features,...

4 minutes read.

Angular 8 *ngFor Directive

Angular 8ngFor Directive The *ngFor directive is used to repeat to repeat a portion of HTML template once per each item from an iterable list (collection). The ngFor is an Angular...

2 minutes read.

Angular 8 App Loading

How an Angular 8 app loaded and started When we create an Angular app and run it by using ng serve command, it looks like the below screenshot. It is a simple...

3 minutes read.

Angular 8 ngClass Directive

Angular 8 ngClass Directive ngClass Directive is a type of attribute directive. Angular provided built-in directive, and it helps in adding or removing CSS classes on an HTML element. The ngClass directive allows...

2 minutes read.

Creating form in Angular 8

The angular reactive form is used to handle the user's input. We can use Angular form in the application to authorize the user to log in, to update profile, to enter information,...

2 minutes read.

Property binding in Angular 8

Property binding is the primary way to binding data in Angular.  To bind data to a property of any element, we use square braces[ ]. It is also a one-way data-binding...

2 minutes read.

Angular 8 Tutorial

What is Angular 8 Angular is a Framework of JavaScript used to build web and mobile applications. Angular 8 is a client-side TypeScript based structure which is used to create dynamic...

6 minutes read.

Angular 8 Module

Angular 8 Module It is a collection of services, directives, controllers, filters, and configuration information. angular.module is used to configure the $injector. The module is a container of the different parts of an application....

6 minutes read.