I am struggling to auto generate the jsonld script in angularjs2, However, I found a solution for angularjs1. Do anyone have solution for this.
-
visit 'stackoverflow.com/questions/35332430/…'Abhinay Reddy Keesara– Abhinay Reddy Keesara2016-07-05 03:48:28 +00:00Commented Jul 5, 2016 at 3:48
-
Hi thanks for your reply, but this solution is for angularjs1 not for version 2 which is completely different.Arvind Chavhan– Arvind Chavhan2016-07-05 03:52:12 +00:00Commented Jul 5, 2016 at 3:52
-
found anything yet?Nicky– Nicky2017-04-20 13:39:58 +00:00Commented Apr 20, 2017 at 13:39
Add a comment
|
2 Answers
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);
}
Comments
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.
5 Comments
Vel
I have same issue. could you please explain how to fix this issue?. Please check this link stackoverflow.com/questions/44389546/…
tooleks
@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.
Vel
I tried with angular universal. But I cannot use use Ng build --prod. That's the problem. How to solve this?
tooleks
@vel, why you can't use it? Can you provide the error logs?
Francis Manoj Fernnado
added smiler example without using a pipe