6

I am struggling to auto generate the jsonld script in angularjs2, However, I found a solution for angularjs1. Do anyone have solution for this.

3
  • visit 'stackoverflow.com/questions/35332430/…' Commented 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. Commented Jul 5, 2016 at 3:52
  • found anything yet? Commented Apr 20, 2017 at 13:39

2 Answers 2

4

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);
      }
Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

I have same issue. could you please explain how to fix this issue?. Please check this link stackoverflow.com/questions/44389546/…
@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.
I tried with angular universal. But I cannot use use Ng build --prod. That's the problem. How to solve this?
@vel, why you can't use it? Can you provide the error logs?
added smiler example without using a pipe

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.