Search code examples
angularkatex

how to import KaTex in Angular17


I am new in KaTex and have no change to import KaTex in Angular 17. Also I tried to install per npm Katex gobal, but also no import in Angular app is possible for me.

My goal is, to display a math formular as (katex)string , created by a function, into the html.


Solution

  • https://katex.org/docs/libs links to https://github.com/garciparedes/ng-katex for Angular support. Have you given that a try? I don't have experience with it, but it sounds like a good starting point.

    If I were to write some integration myself, I'd not use the auto-render extension. That works well for static content but would likely become a pain to manage in the face of any dynamic updates to your content.

    Instead I'd use the innerHTML binding to feed a HTML string from your component TypeScript into the DOM. So you would have <span [innerHTML]="katexMarkup()"></span> and then define a function katexMarkup to fill that.

    https://katex.org/docs/api documents a renderToString function which you can use to implement that. To call this you need to get your hands on the katex namespace / module. Personally I would load it globally, using its own top level tags as documented in https://katex.org/docs/browser. This is assuming that you want KaTeX available everywhere in your Angular app, and not just load it on demand when needed. Inside the Angular code you could then access the window object to gain access to that katex object. Something like (window as any)['katex'].renderToString(tex) (untested). Of course, a proper Angular approach would put one layer of dependency injection between this, so that you can replace the actual KaTeX library with something simpler and less likely to change for your unit tests.

    The ng-katex project appears to avoid the indirection via a string, and has the library build DOM nodes directly. I assume one needs to have a better understanding of Angular than I have to get that done right.