import { Component, OnInit, OnDestroy, Input, Output, ElementRef, EventEmitter } from '@angular/core'; import { SafeHtml, DomSanitizer } from '@angular/platform-browser'; import * as hljs from 'highlight.js'; import * as Clipboard from 'clipboard'; import 'highlight.js/styles/docco.css'; @Component({ selector: 'cm-code-highlight', templateUrl: './code-highlight.component.html', styleUrls: ['./code-highlight.component.css'] }) export class CodeHighlightComponent implements OnInit, OnDestroy { _hlString: string; safeHtml: SafeHtml; clipboard: any; @Output() onCopy = new EventEmitter(); constructor( private el: ElementRef, private sanitizer: DomSanitizer) { } @Input() set hlString(hlString: string) { this._hlString = hlString; this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(hljs.highlightAuto(this._hlString).value); } ngOnInit() { let self = this; let clipAction = (this.el.nativeElement as HTMLElement).querySelector('.clip-button'); self.clipboard = new Clipboard(clipAction, { text: function (trigger) { return self._hlString; } }); self.clipboard.on('success', function (e: any) { self.onCopy.emit(true); }); self.clipboard.on('error', function (e: any) { self.onCopy.emit(false); }); } ngOnDestroy() { this.clipboard.destroy(); } }