How to get Mathjax working with Angular2?

前提是你 提交于 2019-11-29 02:19:52

I would implement this way with an input to get the specified expression:

import {Directive, ElementRef, Input} from 'angular2/core';
@Directive({
    selector: '[MathJax]'
})
export class MathJaxDirective {
    @Input(' MathJax')
    texExpression:string;

    constructor(private el: ElementRef) {
    }

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

And use this way:

<textarea #txt></textarea>
<span [MathJax]="txt.value"></span>

See this plunkr: http://plnkr.co/edit/qBRAIxR27zK3bpo6QipY?p=preview.

Based on this question, I started the development of an open source project to typeset TeX math expressions with Angular. The project is on https://github.com/garciparedes/ng-katex.

You can install the module with:

npm install ng-katex --save

To add the module to your proyect add the KatexModule to import's field of your parent module:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';

import { KatexModule } from 'ng-katex';

@NgModule({
  imports: [BrowserModule, KatexModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})

class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);

And then you can use it as follows:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<ng-katex [equation]="equation">`
})
export class AppComponent {
  equation: string = ''\sum_{i=1}^nx_i'';
}

Used Mathjax in my project in Angular 2 as follows:

setTimeout(function () { MathJax.Hub.Queue(["Typeset", MathJax.Hub]);}, 5);

as the queue runs asynchronously, the setTimeout ensures the math rendering process happens after a certain point of time.

The problem is that template generator of angular 2 looking for end of file char '{' or finds something unexpected inside the html file at the end of file(EOF).

In order to be able to use MathJax with Angular 2 template generator:

<h1>example not working = $$ 2^{x + 2 } $$</h1>

<h1>example working = $$ 2^{{ '{' }} x + 2 {{ '}' }} $$</h1>

Just use {{ '{' }} or {{ '}' }} , instead of simple '{' inside the html tags.

Dont forget to add this to your index.html tags :

<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!