'Using MathJax inside Typescript/Angular2 component
I'm having trouble calling the MathJax.Hub functions in my angular2 component. I have struggled over this for many hours last night. I need to call the MathJax API to re render some InnerHTML string that is dynamically binded. The problem is, no matter how I import the MathJax module or npm install it, I can't access the MathJax global variable in my component.ts. I verified this with trying MathJax.version and the compiler complains about can't finding version of undefined.
I have run npm install MathJax in my module. Run npm install @typings mathjax. Have tried importing mathjaxdirective. In the sample HTML provided upon mathjax install, I can see that formatting is correctly applied. What is the right way to gain access to the MathJax global variable inside my typescript?
Solution 1:[1]
I found a simple solution. It as follows:
Add the following code in index.html
<script type="text/x-mathjax-config"> MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}}); </script> <script type="text/javascript" async src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML"> </script>Add this line in your typescript file as an import:
declare var MathJax:any;Use mathjax:
MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
Solution 2:[2]
According to the article 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.
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:
<div class="math-element" id="equation" [mathJax]="equationTexString"></div>On the other hand, remember add the MJD directive into the component directive list:
@Component({ selector: "equation-component", directives: [MJD], }) export class EquationComponent { private equationTexString: string = ""; }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sourabh Dev |
| Solution 2 | KyleMit |
