×

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

String Interpolation in Angular 8

String Interpolation in Angular 8 String interpolation is a one-way data-binding technique which is used to output the data from a typescript code to HTML template. It uses the template expression. It uses the...

2 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.

Deployment of an Angular 8 app

Deploying an Angular 8 app To implement our application, we have to compile it and then host the JavaScript, CSS, and HTML on a web server. Build an Angular application which is very portable...

4 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.

How to create a Todo List App in Angular 7

What is a Todo List App? Todo List app is an app where users can add various tasks that they want to perform and have an idea of every task. If...

4 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.

Difference between Node.js and ASP.net

Introduction to Node.js V8 (the JavaScript engine operating inside Google Chrome) is packaged with certain libraries and is mostly used for input & output, which includes creating data and managing connection...

4 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.

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.

Angular 8 with Bootstrap

How to install Bootstrap for Angular? Run the following Command in Command prompt. npm install–save bootstrap@3= > The @3 is essential! After that, when we use a project created with Angular CLI 6+, we will...

1 minute 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.

Scalability and Validation Forms in Angular 8

Form Validation Validation is an essential part of managing any set of forms. If we are checking for required fields or querying an external API for a username. Angular 8 provides a set of...

1 minute 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 Observables

Observables provide support for passing messages between publisher and subscription in our application. The observables can deliver the multiple values of any type like literal, messages, depending on the content. It is an...

6 minutes read.

Data Binding in Angular 8

What is Binding? Binding is the process which generates the connection between the application UI and the data which comes from the business logic. In Angular, it is called the automatic synchronization of...

3 minutes read.

Angular 8 Animation

What is Animation? The animation is a process of drawing, designing, making layouts, and preparation of photographic sequences which are integrated into the multimedia and gaming products. A reflection of movement created for displaying...

5 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.

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.

Creating first APP in Angular 8

Firstly, we have to open Git Bash and, then we have to write the following command in it. ng new my -app The project has been created now so that now we have to go...

2 minutes read.