import { ChangeDetectionStrategy , Component , Input , OnChanges , ViewChild , ViewContainerRef } from '@angular/core' ; import { highlight , languages } from 'prismjs' ; import prism from '!!raw-loader!prismjs' ; @ Component ( { selector : 'uxd-snippet' , templateUrl : './snippet.component.html' , changeDetection : ChangeDetectionStrategy . OnPush } ) export class SnippetComponent implements OnChanges { @ Input ( ) language : string = 'html' ; @ Input ( ) code : string ; @ Input ( ) content : any ; @ Input ( ) synchronous : boolean = false ; @ ViewChild ( 'code' , { read : ViewContainerRef , static : true } ) codeContainer : ViewContainerRef ; constructor ( ) { } ngOnChanges ( ) { if ( this . code ) { this . loadCode ( ) ; } else if ( this . content ) { this . loadContent ( ) ; } } private loadCode ( ) { if ( this . synchronous ) { const code = highlight ( this . code , languages [ this . language ] ) ; this . codeContainer . element . nativeElement . innerHTML = `<code>${ code }</code>` ; return ; } const blob = new Blob ( [ prism ] , { type : 'application/javascript' } ) ; const worker = new Worker ( URL . createObjectURL ( blob ) ) ; worker . onmessage = ( evt ) => { this . codeContainer . element . nativeElement . innerHTML = `<code>${ evt . data }</code>` ; worker . terminate ( ) ; } ; worker . postMessage ( JSON . stringify ( { language : this . language , code : this . code } ) ) ; } private loadContent ( ) { this . codeContainer . element . nativeElement . innerHTML = `<code>${ this . content }</code>` ; } }