@emelie
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:
- Install the ngx-sitemap-generator library using the following command:npm install ngx-sitemap-generator
- Import the NgxSitemapGeneratorModule module in your app module:import { NgxSitemapGeneratorModule } from 'ngx-sitemap-generator';
@NgModule({
imports: [
NgxSitemapGeneratorModule.forRoot('https://example.com')
]
})
export class AppModule { }
The forRoot() method takes the base URL of your website.
- 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.
- Finally, you need to add the sitemap URL to your robots.txt file:Sitemap: https://example.com/sitemap.xml
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.