raisin
raisin

Reputation: 1

How to change the language used in a monaco-editor instance dynamically?

I want to know display languages on Monaco editor.

Example:

When a radio button, labeled "clang" is pushed, the language used by a Monaco editor is to be changed to clang.

Please tell me how to solve this problem.

Upvotes: 0

Views: 3699

Answers (2)

Ehsan Ghaffarii
Ehsan Ghaffarii

Reputation: 50

I did this in a project and it works without bugs, In angular project

Here is how I create my editor:

code.components.ts


@Input() lang: string = 'python';

editorOptions: { theme: string; language: string } | undefined;

if (this.lang === null) {
      throw new Error('Lang is required');
    }
    const [langObject] = this.langs.filter((l: Lang) => l.value === this.lang);
    this.selectedLang = langObject;
    this.editorOptions = {
      theme: this.theme,
      language: langObject.monacoValue,
    }

onLangChange(): void {
    this.lang = this.selectedLang.value;
    this.editorOptions = {
      theme: this.theme,
      language: this.selectedLang.monacoValue,
    };
  }

code.components.html



<div class="code-container py-3">
    <select [(ngModel)]="selectedLang" (change)="onLangChange()">
      <option *ngFor="let l of langs" [ngValue]="l">{{ l.viewValue }}</option>
    </select>
    <ngx-monaco-editor
      [options]="editorOptions"
      [(ngModel)]="sourceCode"
    ></ngx-monaco-editor>
  </div>

This is output

enter image description here

Upvotes: 0

Mike Lischke
Mike Lischke

Reputation: 53367

There's a method on the editor to change a model's language, called setModelLanguage

editor.setModelLanguage(editor.getModel(), "clang");

However, you have to add support for the clang language to Monaco yourself. There's no built-in support for that.

Upvotes: 1

Related Questions