Step 1: Preparing Your Angular Environment

Before diving in, confirm that both Node.js and the Angular CLI are available on your machine. If they're missing, the installation commands are provided below:

npm install -g @angular/cli

Step 2: Scaffolding a Fresh Angular Project

Use the Angular CLI to generate a new project from scratch:

ng new dynamic-sitemap-app

Step 3: Establishing a Server-Side Folder

Inside your Angular workspace, create a separate folder named server. This directory will house all backend-related logic.

Step 4: Installing Dependencies for the Backend

Switch into the newly created server folder and pull in the packages required for the Node.js server:

cd serve
npm init -y
npm install express xmlbuilder

Step 5: Building the Sitemap Generator Server

Within the server directory, add a file called server.js. This script will construct the sitemap XML and expose it over HTTP:

const express = require('express')
const xmlbuilder = require('xmlbuilder');
const app = express();
const PORT = process.env.PORT || 3000;

// Define your application's routes
const routes = [
  '/',
  '/about',
  '/contact',
  // Add more routes as needed
];

app.get('/sitemap.xml', (req, res) => {
  const root = xmlbuilder.create('urlset', { version: '1.0', encoding: 'UTF-8' });
  root.att('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');

  routes.forEach(route => {
    const url = root.ele('url');
    url.ele('loc', `https://yourdomain.com${route}`);
    // You can add more elements like <changefreq> and <priority> here if needed
  });

  res.header('Content-Type', 'application/xml');
  res.send(root.end({ pretty: true }));
});

app.listen(PORT, () => {
  console.log(`Server started on http://localhost:${PORT}`);
});

Step 6: Pointing the Angular Build Output to the Server

Modify the angular.json configuration file so that the outputPath property for your app points to ../dist/client. This ensures the compiled frontend lands where the server expects it.

Step 7: Compiling the Angular App for Production

Run the production build for your Angular application:

ng build --prod

Step 8: Launching the Node.js Server

From the server directory, kick off the server with the following command:

node server.js

Step 9: Viewing the Live Sitemap

Open your browser and navigate to http://localhost:3000/sitemap.xml to see the freshly generated sitemap in action.

That's all there is to it—dynamic sitemap generation for your Angular app is now up and running, powered by a Node.js and Express backend. This setup aids search engine crawlers in indexing your pages and strengthens your overall SEO. Feel free to tailor the server configuration and sitemap generation rules to match your specific routes and content needs.