5

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

Arvind Chavhan
  • 488
  • 1
  • 6
  • 14

2 Answers2

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);
      }
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
  • @vel, why you can't use it? Can you provide the error logs? – tooleks Jun 12 '17 at 17:28
  • added smiler example without using a pipe – Francis Manoj Fernnado Aug 13 '17 at 12:19