I am using Angular 17 with SSR configuration enabled and complete standalone component architecture and want to insert structured data in different components for rich snippet and better SEO crawling.
example:
I searched for different ways to do it and came across few ideas of doing it like bellow:
constructor(private meta:Meta){
meta.addTag({name:'application/ld+json' , content:JSON.stringify(STRUCTURED_DATA_OBJECT)});
}
But this is not what I want , I want to add the structured data object inside <script>
tag separate for each standalone components.
11
I have found a way to do that using Renderer2
See the code below for reference 👇
Use this code in whichever component you want to add the structured data.
import {Inject, Renderer2 } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Component({...})
export class CustomClass implements OnInit{
constructor(private _renderer:Renderer2 , @Inject(DOCUMENT) private _document:Document){}
public ngOnInit(){
let script = this._renderer.createElement('script');
script.type = 'application/ld+json';
script.text = `{data}`; /*Insert the data you want to add*/
this._renderer.appendChild(this._document.body, script);
}
1