id | title | date | author | layout | guid | permalink | dsq_thread_id | image | categories | tags | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
904 |
Add highlight.js to an Angular 2 application |
2017-02-13 20:44:45 +0000 |
Marco Molteni |
post |
/2017/02/13/add-highlight-js-to-an-angular-2-application/ |
|
/wp-content/uploads/2017/03/logo-highlightjs-100x38.png |
|
|
With the goal to build my own blog application (for educational purposes) I integrated the highlight.js library in the demo application.
At the moment there are problems with safari and mobile platforms, a js error in the library.
The implementation is based on this answer in Stack Overflow (thanks to the author) 😉
In packages.json you have to import the highlight library and the type:
'highlight.js': '^9.9.0', '@types/highlight.js': '^9.1.9',
The implementation is done via a directive:
import {Directive, ElementRef, AfterViewInit} from '@angular/core'; import * as hljs from 'highlight.js'; @Directive({ selector: 'code[ highlight]' // css selector for the attribute }) export class HighlightCodeDirective implements AfterViewInit{ constructor(private eltRef:ElementRef) { } ngAfterViewInit() { hljs.highlightBlock(this.eltRef.nativeElement); } }
The html code of the example:
and the result: