How to create a sitemap dynamically in Angular 12?


by emelie , in category: SEO , 7 months ago

How to create a sitemap dynamically in Angular 12?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by jose_gulgowski , 7 months ago


To create a sitemap dynamically in Angular 12, you can use a library called ngx-sitemap-generator.

Here are the steps to use this library:

  1. Install the ngx-sitemap-generator library using the following command:npm install ngx-sitemap-generator
  2. Import the NgxSitemapGeneratorModule module in your app module:import { NgxSitemapGeneratorModule } from 'ngx-sitemap-generator'; @NgModule({ imports: [ NgxSitemapGeneratorModule.forRoot('') ] }) export class AppModule { } The forRoot() method takes the base URL of your website.
  3. In your component, import the SitemapService and call its generateSitemap() method to generate the sitemap:import { Component } from '@angular/core'; import { SitemapService } from 'ngx-sitemap-generator'; @Component({ selector: 'app-root', template: '<h1>Hello, World!</h1>' }) export class AppComponent { constructor(private sitemapService: SitemapService) {} ngOnInit() { this.sitemapService.generateSitemap(); } } You can call the generateSitemap() method whenever you want to update the sitemap.
  4. Finally, you need to add the sitemap URL to your robots.txt file:Sitemap:

That's it! Now, whenever you run your Angular app, the sitemap will be generated dynamically and the robots.txt file will include the sitemap URL.