Reputation: 488
I am struggling to auto generate the jsonld script in angularjs2, However, I found a solution for angularjs1. Do anyone have solution for this.
Upvotes: 5
Views: 944
Reputation: 262
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);
}
Upvotes: 3
Reputation: 585
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.
Upvotes: 2