0

My problem relies in these two lines of Angular code :

<div *ngIf="timer$ | async as timer"> {{timer}}</div>
<ng-katex-paragraph [paragraph]="formula"></ng-katex-paragraph>

enter image description here The first line is a simple timer that refreshes every 100th second. The second line is a third-party library ("ng-katex"), that displays a mathematical formula (from the string formula)

Issue : every time the timer refreshes, the formula is refreshed as well (like : re-generated), and it takes time. As a consequence the timer is slowed down.

If I had control over the Katex library, I would set changeDetectionStrategy to "onPush" inside it, but Katex is a third party library, so how could I force it to not refresh ?

Thanks for your help ! Here is a minimal repro : https://stackblitz.com/edit/angular-vafchf

Serge

1 Answer 1

1

The easiest solution is to wrap the formula component into a component of its own, and set its change detection strategy to ChangeDetectionStrategy.OnPush like this:

// wrap the base component into an onpush.
@Component({
  selector: "my-formula",
  template: `<ng-katex-paragraph [paragraph]="paragraph">
             </ng-katex-paragraph>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyFormulaComponent {
  @Input("paragraph")
  paragraph: string = '';
}

and change your component html to use it like this:

<div *ngIf="timer$ | async as timer"> {{timer}}</div>
<my-formula [paragraph]="formula"></my-formula>

Don't forget to register the new component into your AppModule:

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

Needless to say, you will have to manage the push strategy yourself of the formulas, using changeDectorRef, see: https://angular.io/api/core/ChangeDetectorRef

Sign up to request clarification or add additional context in comments.

1 Comment

Glad that helped :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.