5. Step-by-Step: Building an Angular SPA
Step 1: Set up your environment
You will need:
- Node.js (an active LTS version supported by your Angular version)
- A code editor such as VS Code
- Angular CLI, installed with:
bash
npm install -g @angular/cli
Step 2: Create the project
bash
ng new customer-portal –routing –style=scss
cd customer-portal
ng serve
Open http://localhost:4200 and you will see your app running. The CLI generates a project structure, TypeScript configuration, a testing setup, and a build pipeline, which is a big part of Angular’s appeal for teams.
Step 3: Plan your folder structure
Resist the urge to dump everything in one folder. A structure that scales well is feature-based:
src/app/
core/ (auth service, interceptors, guards, app-wide singletons)
shared/ (reusable UI components, pipes, directives)
features/
dashboard/
customers/
invoices/
settings/
Each feature folder owns its components, services, and routes. This makes the code easier to navigate, test, and eventually split apart if the app grows.
Step 4: Build components
Generate a component:
bash
ng generate component features/customers/customer-list
A simple standalone component might look like this:
typescript
import { Component, inject, signal } from ‘@angular/core’;
import { CustomerService } from ‘../customer.service’;
@Component({
selector: ‘app-customer-list’,
standalone: true,
template: `
<h1>Customers</h1>
@if (loading()) {
<p>Loading…</p>
} @else {
<ul>
@for (c of customers(); track c.id) {
<li>{{ c.name }}</li>
}
</ul>
}
`,
})
export class CustomerListComponent {
private service = inject(CustomerService);
customers = signal<Customer[]>([]);
loading = signal(true);
constructor() {
this.service.getAll().subscribe(data => {
this.customers.set(data);
this.loading.set(false);
});
}
}
Keep components focused. If a component is doing data fetching, business rules, and layout all at once, split it up.
Step 5: Configure routing
typescript
// app.routes.ts
import { Routes } from ‘@angular/router’;
export const routes: Routes = [
{ path: ”, redirectTo: ‘dashboard’, pathMatch: ‘full’ },
{
path: ‘dashboard’,
loadComponent: () =>
import(‘./features/dashboard/dashboard.component’)
.then(m => m.DashboardComponent),
},
{
path: ‘customers’,
loadChildren: () =>
import(‘./features/customers/customers.routes’)
.then(m => m.CUSTOMER_ROUTES),
},
{ path: ‘**’, loadComponent: () =>
import(‘./core/not-found.component’).then(m => m.NotFoundComponent) },
];
typescript
// app.config.ts
import { ApplicationConfig } from ‘@angular/core’;
import { provideRouter, withComponentInputBinding } from ‘@angular/router’;
import { provideHttpClient, withInterceptors } from ‘@angular/common/http’;
import { routes } from ‘./app.routes’;
import { authInterceptor } from ‘./core/auth.interceptor’;
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, withComponentInputBinding()),
provideHttpClient(withInterceptors([authInterceptor])),
],
};
Two things worth noticing. First, loadComponent and loadChildren enable lazy loading, so users download code for a feature only when they need it. That has a direct effect on initial load speed. Second, always include a wildcard route so mistyped URLs land on a helpful page rather than a blank screen.
Then place <router-outlet /> in your root component’s template. That is where routed components appear.
Step 6: Protect routes with guards
Not every user should see every page. Functional route guards check permissions before navigation completes:
typescript
import { inject } from ‘@angular/core’;
import { CanActivateFn, Router } from ‘@angular/router’;
import { AuthService } from ‘./auth.service’;
export const authGuard: CanActivateFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.isLoggedIn() ? true : router.createUrlTree([‘/login’]);
};
Attach it to routes with canActivate: [authGuard].
A critical point that many business owners miss: route guards improve user experience, but they do not provide security. Anyone can inspect front-end code. Real authorization must be enforced on the server for every API call. Guards simply prevent users from stumbling into screens they cannot use.
Step 7: Connect to your backend with HttpClient
Create a service to keep API calls out of your components:
typescript
@Injectable({ providedIn: ‘root’ })
export class CustomerService {
private http = inject(HttpClient);
private baseUrl = ‘/api/customers’;
getAll() {
return this.http.get<Customer[]>(this.baseUrl);
}
getById(id: number) {
return this.http.get<Customer>(`${this.baseUrl}/${id}`);
}
}
Add an interceptor to attach authentication tokens and handle errors centrally, rather than repeating logic in every call. Typed responses (Customer[]) catch a surprising number of bugs at compile time.
Step 8: Build forms properly
Business apps live and die by their forms. Angular offers reactive forms, which give you explicit control over validation, dynamic fields, and complex rules:
typescript
form = new FormGroup({
name: new FormControl(”, [Validators.required, Validators.minLength(2)]),
email: new FormControl(”, [Validators.required, Validators.email]),
province: new FormControl(‘ON’, Validators.required),
});
Step 9: Manage state sensibly
- Start simple. Signals and services are enough for many apps.
- Add a store when complexity demands it. Libraries such as NgRx (or the lighter NgRx Signals) help when many components share complex state and you need predictable updates and debugging tools.
- Don’t over-engineer. Introducing a heavy state library into a ten-screen app adds ceremony without benefit.
Step 10: Handle errors and loading states
Users will hit slow networks and server errors. Plan for them from day one: loading indicators, friendly error messages, retry options, and a global error handler that logs problems for your team. An app that fails gracefully feels professional. One that shows a blank screen feels broken.
Step 11: Test as you go
Angular's CLI sets up unit testing out of the box. A healthy testing approach includes:
- Unit tests for services and business logic
- Component tests for important UI behaviours
- End-to-end tests for critical journeys such as login, checkout, and submitting a form
Step 12: Build and deploy
bash
ng build –configuration production
The production build minifies code, removes unused parts (tree shaking), and produces optimized bundles. Deploy the output to a hosting platform such as Azure Static Web Apps, AWS (S3 with CloudFront), Google Cloud, or a container platform. Pair it with a CI/CD pipeline (GitHub Actions, Azure DevOps, or GitLab CI) so every change is tested and released consistently.