Build powerful one-page apps using Angular
Learn how to build an Angular single page application (SPA) with routing, REST API integration, lazy loading, testing, and performance optimization tips.
In the modern web development landscape, users expect fast, seamless, and dynamic web experiences. Traditional multi-page applications (MPAs) often fall short in terms of speed and user interaction. This is where Angular single page applications (SPAs) shine.
If you’ve ever used Gmail or Facebook, you’ve interacted with an SPA — a web app that loads a single HTML page and dynamically updates content without refreshing the page. This blog will teach you everything you need to know to build your own single page application website using Angular.
We’ll dive deep into Angular’s architecture, lazy loading modules, REST API integration, and explore the best practices for Angular module structure, unit testing, and performance optimization in Angular. By the end, you’ll have a clear roadmap to build production-ready SPAs.
A Single Page Application (SPA) is a web application or site that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from the server.
When you build an Angular one page application, Angular handles routing on the client side using the Angular Router module.
Why Use SPA in Angular?
Fast and responsive user experience
Less server load and bandwidth usage
Clean separation between front-end and back-end
Smooth navigation without full-page reloads
Let’s break down the core features that make Angular a great choice for SPAs:
1. Angular Router
Angular’s routing system enables navigation within your app without page reloads.
const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'about', component: AboutComponent }, ];
Use the <router-outlet></router-outlet> tag in your main template to load route components dynamically.
2. Two-Way Data Binding
This allows your UI and model to stay in sync in real time.
3. Dependency Injection
Simplifies service management across components.
4. Angular CLI
Speeds up development with powerful tools for scaffolding and testing.
Let’s build a basic Angular single page app.
Step 1: Create Angular App
ng new angular-spa-demo cd angular-spa-demo ng serve
Step 2: Set Up Routing
When prompted, choose Yes for routing during setup.
Create components:
ng generate component home ng generate component about
Update app-routing.module.ts:
const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'about', component: AboutComponent } ];
Add router outlet in app.component.html:
<router-outlet></router-outlet>
Lazy loading helps optimize performance by loading modules only when needed.
ng generate module admin --route admin --module app.module
This command sets up a separate route and lazy loads the AdminModule.
Lazy loading is a key feature of any performance optimization in Angular app structure.
You can also integrate Angular with single-spa (a JavaScript framework for building microfrontends). This is useful in enterprise apps where multiple teams work on different modules.
Single SPA Angular Setup:
Install single-spa CLI
Scaffold Angular microfrontend
Register multiple Angular apps under one root config
This architecture allows multiple Angular single page apps to coexist independently, sharing resources when necessary.
To fetch or post data, Angular uses its powerful HttpClientModule.
Step-by-step:
Import HttpClientModule in app.module.ts
Create a service to handle API calls
getUsers() { return this.http.get('https://jsonplaceholder.typicode.com/users'); }
Inject the service in your component and call getUsers()
Use Case:
Integrating a back-end API in your Angular single page application is essential for tasks like user authentication, data management, form submissions, etc.
Keeping your Angular app scalable and maintainable is key. Here are some tips:
Use feature modules (admin, auth, dashboard)
Separate shared module for common components
Lazy load non-essential modules
Keep services in their own folders
Maintain strict typing and folder hygiene
By following these practices, you make your code more readable, testable, and developer-friendly.
Testing is crucial for any professional Angular SPA. Angular uses Karma and Jasmine for unit testing.
Test a Service:
it('should fetch users', () => { const dummyUsers = [{ name: 'John' }]; service.getUsers().subscribe(users => { expect(users.length).toBe(1); expect(users).toEqual(dummyUsers); }); const req = httpMock.expectOne('https://api.example.com/users'); expect(req.request.method).toBe("GET"); req.flush(dummyUsers); });
Test a Component:
it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app).toBeTruthy(); });
Here are some advanced techniques for SPA performance:
Lazy loading modules
Use trackBy in *ngFor to prevent unnecessary DOM updates
ChangeDetectionStrategy.OnPush for components
Use environment-specific production build
AOT Compilation for faster rendering
Use async pipe to manage subscriptions
*ngFor="let item of items; trackBy: trackById"
Use the Angular CLI to build for production:
ng build --prod
Deploy your /dist folder to any server or use Firebase Hosting, Netlify, Vercel, or GitHub Pages.
Creating an Angular single page application gives users a dynamic, high-performance experience. With routing, lazy loading, API integration, and solid architecture, Angular provides everything needed for building modern SPAs.
This blog explored:
What is SPA in Angular
Lazy loading and modular architecture
REST API communication
Unit testing and performance best practices
Whether you're building a small tool or a large-scale enterprise solution, Angular makes it scalable and maintainable.
Multiple-choice questions and correct answers with explanations:
1. Which of the following is not a primitive data type in TypeScript?
A) number
B) string
C) boolean
D) object
2. How do you define an array of strings in TypeScript?
A) let arr: string[] = ["a", "b", "c"];
B) let arr: Array<string> = ["a", "b", "c"];
C) let arr: [string] = ["a", "b", "c"];
D) Both A and B
3. What is the correct way to define a tuple in TypeScript?
A) let tuple: [string, number] = ["hello", 10];
B) let tuple: (string, number) = ["hello", 10];
C) let tuple: [string; number] = ["hello", 10];
D) let tuple: {string, number} = ["hello", 10];
4. Which of the following denotes an object type with specific properties in TypeScript?
A) let obj: { name: string, age: number };
B) let obj: (name: string, age: number);
C) let obj: [name: string, age: number];
D) let obj: { name; string, age; number };
5. How do you define a function type in TypeScript that takes a number and returns a string?
A) let myFunc: (x: number) => string;
B) let myFunc: (x: number): string;
C) let myFunc: {x: number}: string;
D) let myFunc: [x: number]: string;
6. What is the TypeScript type for a variable that can hold any value?
A) any
B) unknown
C) object
D) void
7. Which of the following types represents the absence of a value?
A) null
B) undefined
C) void
D) All of the above
8. How do you declare a constant variable in TypeScript?
A) const PI: number = 3.14;
B) let PI: number = 3.14;
C) var PI: number = 3.14;
D) PI: number = 3.14;
9. What is the result of the following TypeScript code? let x:any = "Hello"; x = 10;
A) Compile-time error
B) Runtime error
C) No error, x can be reassigned to any type
D) Undefined behavior
10. Which TypeScript feature allows a variable to hold more than one type?
A) Union types
B) Intersection types
C) Any type
D) Tuple types
11. What is the correct way to cast a variable to a specific type in TypeScript?
A) let str = <string>someVariable;
B) let str = someVariable as string;
C) Both A and B
D) Neither A nor B
12. How do you define an interface in TypeScript?
A) interface Person { name: string; age: number; }
B) class Person { name: string; age: number; }
C) type Person = { name: string; age: number; }
D) let Person = { name: string; age: number; }
13. Which TypeScript type is used for a variable that can be a function or null?
A) Function | null
B) any
C) unknown
D) object
14. How do you define an enum in TypeScript?
A) enum Direction { Up, Down, Left, Right }
B) const Direction { Up, Down, Left, Right }
C) let Direction = { Up, Down, Left, Right }
D) var Direction { Up, Down, Left, Right }
15. Which of the following correctly defines a generic function in TypeScript?
A) function identity<T>(arg: T): T { return arg; }
B) function identity(arg: any): any { return arg; }
C) function identity<T>(arg: any): any { return arg; }
D) function identity(arg: T): T { return arg; }
1. What is Angular interpolation used for?
A) Binding properties of DOM elements to component data
B) Executing component methods
C) Embedding dynamic expressions in the HTML template
D) Creating new Angular components
2. Which of the following is the correct syntax for Angular interpolation?
A) {{ value }}
B) [[ value ]]
C) { value }
D) ( value )
3. What will be the output of {{ 2 + 2 }} in Angular?
A) 22
B) 4
C) {{ 2 + 2 }}
D) Undefined
4. Can you call a method within an Angular interpolation expression?
A) Yes, you can call methods within interpolations.
B) No, methods cannot be called within interpolations.
C) Only if the method is an arrow function.
D) Only if the method returns a string.
5. What will be the output of {{ user.name }} if user is { name: 'John' }?
A) user.name
B) {{ user.name }}
C) John
D) Undefined
6. Which of the following is NOT a valid Angular interpolation expression?
A) {{ 'Hello ' + name }}
B) {{ name ? 'Hi ' + name : 'Hi' }}
C) {{ user['name'] }}
D) {{ name && age }}
7. How do you display a component's property using interpolation?
A) [property]
B) {{ property }}
C) { property }
D) (property)
8. Which of the following expressions will correctly display a user's full name?
A) {{ user.firstName + ' ' + user.lastName }}
B) {{ user.firstName user.lastName }}
C) {{ user.firstName, user.lastName }}
D) {{ user.firstName & user.lastName }}
9. What will be the result of `{{ 5 > 3 }}` in Angular interpolation?
A) 5 > 3
B) true
C) false
D) Undefined
10. How do you format a date using interpolation in Angular?
A) {{ date | date:'shortDate' }}
B) {{ date.date:'shortDate' }}
C) {{ date shortDate }}
D) {{ date, 'shortDate' }}
Whether you're a solo developer or part of an enterprise team, Cyberinfomines can help you with consulting, architecture design, and advanced Angular training.
Got questions or need expert help with your Angular project? Let’s connect.
📞 Call us: +91-8587000904, 8587000906, 9643424141
🌐 Visit: www.cyberinfomines.com
📧 Email: vidhya.chandel@cyberinfomines.com