Open In App

How Single Page Applications work in Angular ?

Last Updated : 28 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In traditional web applications, each time a user interacts with a website, the server sends a new HTML page back to the browser. This process can be slow and inefficient, resulting in a less-than-optimal user experience. Single Page Applications (SPAs) solve this problem by loading all necessary resources and content into a single page, allowing for faster and more responsive interactions.

A Single Page Application is a web application that loads a single HTML page and dynamically updates the content as the user interacts with the application. Instead of requesting a new page from the server each time the user interacts with the application, a SPA loads all necessary resources and content up front and uses client-side rendering to update the page dynamically. SPAs are important because they provide a faster and more responsive user experience compared to traditional web applications. By loading all necessary resources up front, SPAs reduce the amount of time it takes for pages to load and content to appear on the screen. SPAs also allow for more seamless interactions between the user and the application, resulting in a more natural and intuitive user experience. The design pattern used in SPAs is based on client-side rendering, where the majority of the application logic and rendering occurs in the user’s browser instead of on the server. This allows for faster and more efficient processing of user interactions, resulting in a smoother user experience.

Working of SPAs: The working of a SPA involves the following steps:

  • The initial HTML, CSS, and JavaScript files are loaded into the browser when the user first accesses the application.
  • As the user interacts with the application, the browser sends requests to the server for data, which is returned as JSON or XML.
  • The application uses JavaScript to parse the data and dynamically update the page without requiring a full page reload.
  • The application uses client-side routing to manage the display of different views and components within the application.

 

Some of the Main Components used in a SPA:

  • Components: Angular components are reusable building blocks that can be combined to create complex user interfaces. Each component is responsible for rendering a view, handling user events, and communicating with services to obtain data.
  • Services: Angular services provide a way to encapsulate common functionality that can be reused throughout an application. Services can be used to retrieve data from a server, handle authentication, or provide utility functions.
  • Directives: Angular directives allow developers to extend the HTML syntax to create reusable components that can be used throughout an application. Directives can be used to add behavior to existing elements, such as creating a tooltip or adding a custom attribute to form input.
  • Dependency Injection: Angular’s dependency injection system provides a way to manage the creation and lifecycle of objects in an application. This allows developers to create modular, testable code by separating concerns and creating reusable services that can be injected into different components.

For a detailed description of all the components, refer to the Angular 7 Architecture article.

Example 1: The below example illustrates the approach to implement & the working of the Single Page Applications in Angular.

  • Install Node.js on your computer if it is not already installed. You can download it from the Node.js website.
  • Open a command prompt or terminal window and run the following command to install the Angular CLI:
npm install -g @angular/cli
  • Once the Angular CLI is installed, create a new Angular project by running the following command:
ng new spa

This will create a new Angular project in a directory named “spa”.

  • Change into the project directory by running the following command:
cd spa
  • Create a new component by running the following command:
ng g c home

This will create a new component named “home” in the “src/app” directory.

  • Edit the “src/app/app.component.html” file to add some content. For example, you can add the following:

HTML




<h1 style="color: green;">
    Welcome to my GFG APP!
</h1>
<h3>
    This explains how Single Page 
    Application works in Angular.
</h3>
<router-outlet></router-outlet>


  • Edit the “src/app/app-routing.module.ts” file to define a route for the home component. For example, you can add the following to the routes array:

Javascript




import { NgModule } from '@angular/core';
import { Routes, RouterModule } 
    from '@angular/router';
import { HomeComponent } 
    from './home/home.component';
  
const routes: Routes = [
    { path: '', component: HomeComponent }
];
  
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


  • Edit the “src/app/home/home.component.html” file to add some content. For example, you can add the following:

HTML




<h4>This is the home page.</h4>


  • The app.module.ts file will contain the following code:

Javascript




import { NgModule } from '@angular/core';
import { BrowserModule } 
    from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } 
    from './app-routing.module';
import { AppComponent } 
    from './app.component';
import { HomeComponent } 
    from './home/home.component';
  
@NgModule({
    declarations: [
        AppComponent,
        HomeComponent
    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        FormsModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }


  • Start the Angular development server by running the following command:
ng serve -o

This will start the development server and launch the application in your default web browser.

  • Open your web browser and navigate to “http://localhost:4200”. You should see the home page that you created earlier.

Output:

 

Example 2: This example demonstrates how Single Page Applications work in Angular by showing how changes to the state of the items array are automatically reflected in the view without the need for a page refresh.

  • Install Node.js on your computer if it is not already installed. You can download it from the Node.js website.
  • Open a command prompt or terminal window and run the following command to install the Angular CLI:
npm install -g @angular/cli
  • Create a new Angular project: Once you have installed the Angular CLI, you can create a new Angular project by running the following command:
ng new my-spa-app

This will create a new Angular project with the name my-spa-app.

  • Navigate to the project directory: After creating a new project, navigate to the project directory by running the following command:
cd my-spa-app
  • Generate a new component: To demonstrate how Single Page Applications work, let’s create a new component to display a list of items. Run the following command to create a new component:
ng generate component item-list

This will create a new component with the name item-list.

  • Update the item-list component: Open the item-list.component.html file and replace the default code with the following:

HTML




<h2>Items</h2>
<ul>
    <li *ngFor="let item of items">{{ item }}</li>
</ul>


This code displays a <h2> tag with the text “Items” and a list of items using the *ngFor directive.

  • Update the item-list component: Open the item-list.component.ts file and add the following code:

Javascript




import { Component } from '@angular/core';
  
@Component({
    selector: 'app-item-list',
    templateUrl: './item-list.component.html',
    styleUrls: ['./item-list.component.css']
})
export class ItemListComponent {
    items = ['Item 1', 'Item 2', 'Item 3'];
}


This code creates an array of items and assigns it to the items variable.

  • Update the app.component.html file: Open the app.component.html file and replace the default code with the following:

HTML




<h1 style="color: green;">
    Welcome to my GFG APP!
</h1>
<h3>
    This explains how Single Page 
    Application works in Angular.
</h3>
<app-item-list></app-item-list>


This code loads the item-list component in the app.component.html file.

  • Run the app: To run the app, use the following command:
ng serve --open 

This will compile the app and open it in your default browser at http://localhost:4200/.

  • Update the item-list component: Open the item-list.component.ts file and replace the items array with the following:

Javascript




import { Component } from '@angular/core';
  
@Component( {
    selector: 'app-item-list',
    templateUrl: './item-list.component.html',
    styleUrls: [ './item-list.component.css' ]
} )
export class ItemListComponent {
    items = [ 'Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5' ];
}


This code adds two more items to the items array.

  • Add the following code to app.module.ts file:

Javascript




import { NgModule } from '@angular/core';
import { BrowserModule }
    from '@angular/platform-browser';
import { AppRoutingModule }
    from './app-routing.module';
import { AppComponent } 
    from './app.component';
import { ItemListComponent }
    from './item-list/item-list.component';
  
@NgModule({
    declarations: [
        AppComponent,
        ItemListComponent
    ],
    imports: [
        BrowserModule,
        AppRoutingModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads