Add highlight.js to an Angular 2 application


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'; 
    selector: 'code[ highlight]' // css selector for the attribute 
export class HighlightCodeDirective implements AfterViewInit{ 
    constructor(private eltRef:ElementRef) { 
    ngAfterViewInit() { 

The html code of the example:

and the result:

WebApp built by Marco using SpringBoot 3 and Java 21. App hosted in Switzerland.