Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating monaco editor theme dynamically in angular

I am trying to update the theme of monaco editor dynamically on click of a button. These are my editor configuration:

htmlEditorOptions = {
    theme: "vs-light",
    automaticLayout:true,
    scrollBeyondLastLine: false,
    fontSize: this.font,
    minimap: {
      enabled: false
    },
    language: 'html'
}

This the code in Angular:

<ngx-monaco-editor 
    [ngStyle]="htmlStyle" 
    name="htmlCode" 
    [options]="htmlEditorOptions" 
    [(ngModel)]="htmlCode">
</ngx-monaco-editor>

On click of a button, I am trying to update its theme as follows:

this.htmlEditorOptions.theme="vs-dark";

I am getting the updated object printed on the console an I am able to display the updated object in the view as well. But, the editor theme does not change. However if I initialize the editor with dark theme then it works, but not dynamically. What might I be doing wrong?

like image 383
codingsplash Avatar asked Dec 19 '25 21:12

codingsplash


1 Answers

This can be done by modifying the options input and changing its reference (this is because monaco components use the OnPush change detection strategy).

For example: component.html

<ngx-monaco-editor [options]="editorOptions" [(ngModel)]="code"></ngx-monaco-editor>

component.ts

editorOptions = {theme: 'vs-dark', language: 'javascript'};
....
changeTheme(theme: string) {
  this.editorOptions = { ...this.editorOptions, theme: theme }; // Or 
  Object.assign({}, this.editorOptions, {theme: theme});
}

source: https://github.com/materiahq/ngx-monaco-editor/issues/6

like image 134
Bodhi Avatar answered Dec 21 '25 11:12

Bodhi