Supports MathJax in angular2 with TypeScript

If we use data binding through Angular2 and doing rendering on UI side, we may find that the MathJax text is not rendered. That’s because we need to re-render the string value every time we change it.

There is a simple module example to handle with, which use event handler binded and will be trigered when value changed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { Directive, ElementRef, OnChanges, Input } from "@angular/core";

declare var MathJax: {
Hub: {
Queue: (param: Object[]) => void;
};
};

@Directive({ selector: "[mathJax]" })
export class MJD implements OnChanges {
@Input("mathJax") private value: string = "";

constructor(private element: ElementRef) {}

ngOnChanges() {
this.element.nativeElement.innerHTML = this.value;
MathJax.Hub.Queue(["Typeset", MathJax.Hub, this.element.nativeElement]);
}
}

On the template HTML file, we can use this directive like this:

1
<div class="math-element" id="equation" [mathJax]="equationTexString"></div>

On the other hand, remember add the MJD directive into the component directive list:

1
2
3
4
5
6
7
@Component({
selector: "equation-component",
directives: [MJD],
})
export class EquationComponent {
private equationTexString: string = "";
}