I am struggling to auto generate the jsonld script in angularjs2, However, I found a solution for angularjs1. Do anyone have solution for this.
Asked
Active
Viewed 891 times
5
-
visit 'http://stackoverflow.com/questions/35332430/angularjs-script-tag-json-ld/35333500#35333500' – Abhinay Reddy Keesara Jul 05 '16 at 03:48
-
Hi thanks for your reply, but this solution is for angularjs1 not for version 2 which is completely different. – Arvind Chavhan Jul 05 '16 at 03:52
-
found anything yet? – Nicky Apr 20 '17 at 13:39
2 Answers
3
Solution without using a pipe (somewhat clean way)
Use the this.sanitizer.bypassSecurityTrustHtml provided https://angular.io/guide/security#sanitization-and-security-contexts
In the template
<div [innerHtml]="jsonLDString"></div>
In the component/directive
private jsonld: any;
public jsonLDString: any;
private setJsonldData() {
this.jsonld = {
'@context': 'http://schema.org/',
'@type': 'Service',
'name': this.providerName,
'description': this.providerDescription,
'aggregateRating': {
'@type': 'AggregateRating',
'ratingValue': '3',
'bestRating': '5',
'ratingCount': '3'
},
'url' : this.providerUrl
};
this.jsonLDString = '<script type="application/ld+json">' + JSON.stringify(this.jsonld) + '</script>';
this.jsonLDString = this.sanitizer.bypassSecurityTrustHtml(this.jsonLDString);
}

Francis Manoj Fernnado
- 242
- 2
- 10
2
I found a little bit "ugly" but working solution using "safeHtml" pipe:
import {Pipe, PipeTransform} from '@angular/core';
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
@Pipe({name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(protected sanitized:DomSanitizer) {
}
transform(value:any):SafeHtml {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
By using it in tandem with the Angular Universal, you can insert any script code:
<div [innerHtml]="'<script type=\'application/ld+json\'>' + jsonLdStringifiedObj + '</script>' | safeHtml"></div>
I've tested the output of this code in the Google Structured Data Testing Tool and it works like expected.

tooleks
- 557
- 5
- 17
-
I have same issue. could you please explain how to fix this issue?. Please check this link https://stackoverflow.com/questions/44389546/schema-not-detected-in-google-structured-data-testing-tool – Vel Jun 06 '17 at 13:34
-
@vel, you need to prerender your angular application on a webserver by using Angular Universal in order for the Google structured data testing tool to be able to parse HTML code which includes your structured data. See the example [starter project](https://github.com/robwormald/ng-universal-demo). – tooleks Jun 09 '17 at 17:29
-
I tried with angular universal. But I cannot use use Ng build --prod. That's the problem. How to solve this? – Vel Jun 09 '17 at 20:10
-
-