I used this variant in Angular 9 TypeScript
import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'app-schema-org',
template: '<div [innerHTML]="jsonLD"></div>',
})
export class SchemaOrgComponent implements OnInit {
jsonLD: SafeHtml;
constructor(private sanitizer: DomSanitizer) { }
ngOnInit() {
const json = {
'@context': 'http://schema.org',
'@type': 'Organization',
'url': 'https://google.com',
'name': 'Google',
'contactPoint': {
'@type': 'ContactPoint',
'telephone': '+1-000-000-0000',
'contactType': 'Customer service',
},
};
// Basically telling Angular this content is safe to directly inject into the dom with no sanitization
this.jsonLD = this.getSafeHTML(json);
}
getSafeHTML(value: {}) {
const json = JSON.stringify(value, null, 2);
const html = `<script type="application/ld+json">${json}</script>`;
// Inject to inner html without Angular stripping out content
return this.sanitizer.bypassSecurityTrustHtml(html);
}
}
And then called it <app-schema-org></app-schema-org>
For me the example above (https://stackoverflow.com/a/47299603/5155484) has no sense because it imports OnInit and implements OnChange and uses ngOnInit with a parameter for changes.
So here is my working fixed example.