Search code examples
javascriptangulartypescriptmathjax

Use MathJax in ngFor Angular (2/4/5)


So, I've been trying to render mathematical equations on Angular 4 application using MathJax. Everything is working fine till I had to render single equation. But now I need to render the around 4 equations which is coming from an API.

Now, using the MathJax inside ngFor works only for the first object in the array but not after that. See screenshot below:

enter image description here

My HTML looks like this:

<div class="card">
    <div class="card-header">
        //question HTML
    </div>
    <div *ngFor="let answer of model.question?.options">
        <span class="answers" #answers>{{answer?.text}}</span>
    </div>
</div>

And, the component looks like this:

@ViewChild('equation') equation: ElementRef;

MathJax.Hub.Queue(["Typeset", MathJax.Hub, this.equation.nativeElement]);
MathJax.Hub.Queue(["Typeset", MathJax.Hub, this.answers.nativeElement]);

Solution

  • Try:

    <div class="card">
        <div class="card-header">
            //question HTML
        </div>
        <div *ngFor="let answer of model.question?.options">
            <span class="answers">{{answer?.text}}</span>
        </div>
    </div>
    

    @ViewChild('equation') equation: ElementRef;
    
    MathJax.Hub.Queue(["Typeset", MathJax.Hub, this.equation.nativeElement]);
    MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementsByClassName("answers")]);
    

    '# sintaxis is unique.