Git Product home page Git Product logo

ngx-monaco-editor's Introduction

Resources

Angular versions

The library is currently supported by Angular v13.

Check older versions support:

  • Angular v6/v7: v2.x
  • Angular v8: v4.x
  • Angular v9 to v12: 5.x

Standard installation

Install from npm repository:

npm install monaco-editor @materia-ui/ngx-monaco-editor --save

Add the glob to assets in angular.json (to make monaco-editor lib available to the app):

{
    ...
    "projects": {
      "YOUR_APP_NAME": {
          ...
          "architect": {
              "build": {
                ...
                "options": {
                    ...
                    "assets": [
                        { "glob": "**/*", "input": "node_modules/monaco-editor", "output": "assets/monaco-editor/" }
                    ],
                    ...
                }
                ...
              }
            }
            ...
        }
    },
    ...
}

Sample

Include MonacoEditorModule in Main Module and Feature Modules where you want to use the editor component.(eg: app.module.ts):

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { MonacoEditorModule } from '@materia-ui/ngx-monaco-editor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    MonacoEditorModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Create Editor options in component.(eg: app.component.ts)

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  editorOptions = {theme: 'vs-dark', language: 'javascript'};
  code: string = 'function x() {\nconsole.log("Hello world!");\n}';
  originalCode: string = 'function x() { // TODO }';
}

Include editor component in your html with options input and ngModel bindings (eg: app.component.html) or using ReactiveForm features.

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

Include diff-editor component in your html and use the following inputs: options, original and modified (eg: app.component.html).

<ngx-monaco-diff-editor [options]="editorOptions" [original]="originalCode" [modified]="code"></ngx-monaco-diff-editor>

Both components support all available monaco-editor options:

Configure default monaco-editor library path

You can configure the default path used to load the monaco-editor library.

It allows you to either change the localization of your local installed library or load the library from a remote resource.

Example load monaco-editor from a CDN:

⚠️ Warning: in this case you don't need to install monaco-editor and neither modify angular.json.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { MonacoEditorModule, MONACO_PATH } from '@materia-ui/ngx-monaco-editor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    MonacoEditorModule
  ],
  providers: [{
    provide: MONACO_PATH,
    useValue: 'https://unpkg.com/[email protected]/min/vs'
  }],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Access editor instance

If you need to retrieve an editor instance you can do so by using the init output:

<ngx-monaco-editor [options]="editorOptions" [(ngModel)]="code" (init)="editorInit($event)"></ngx-monaco-editor>
import { Component } from '@angular/core';
...
export class AppComponent {
  editorOptions = {theme: 'vs-dark', language: 'javascript'};
  code: string= 'function x() {\nconsole.log("Hello world!");\n}';

  editorInit(editor) {
    // Here you can access editor instance
     this.editor = editor;
    }
}

Access Monaco instance

If you need to retrieve monaco-editor instance for advance use cases (like defining a custom theme, add custom auto-complete support, etc...), you have to wait until monaco is loaded using our MonacoEditorLoaderService:

import { MonacoEditorLoaderService } from '@materia-ui/ngx-monaco-editor';
...
constructor(private monacoLoaderService: MonacoEditorLoaderService) {
      this.monacoLoaderService.isMonacoLoaded$.pipe(
        filter(isLoaded => isLoaded),
        take(1),
      ).subscribe(() => {
           // here, we retrieve monaco-editor instance
           monaco.setTheme(...);
      });
     }

Motivations

We wanted to use monaco-editor library with angular in our desktop application: Materia Designer.

The current angular libraries did not cover all of our needs, notably:

  • Works on Browser and Electron application,
  • Support flex-box container and correctly resize editor when container size changes.

ngx-monaco-editor's People

Contributors

batnyu avatar geoastronaute avatar gorunovanton avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

ngx-monaco-editor's Issues

Setup question

The demo on Stackblitz does not have

"assets": [
                        { "glob": "**/*", "input": "node_modules/monaco-editor", "output": "assets/monaco-editor/" }
                    ],

Is it necessary?
And should it be

{ "glob": "**/*", "input": "node_modules/@materia-ui/ngx-monaco-editor", "output": "assets/monaco-editor/" }

Too Many Chunks on Serve and Build

The package generates too many chunks on ng serve and ng build - about 60, which is unacceptable in terms of loading speed CLI tries to increase.

parsedError can be undefined

Hi,

When form with editor is loaded form is marked as dirty.
I did some research and found that in registerEditorListeners method variable hasValidationStatusChanged will resolve to true when control initialized and no changes were made.
This is due to the fact that this.parsedError resolves to undefined and currentParsedError is '' so following line will resolve to true:
const hasValidationStatusChanged = this.parsedError !== currentParsedError;

This causing control to be flagged as modified and when its part of FormGroup it marks the whole form as dirty.

I am using ngx-monaco-editor as follow:
<ngx-monaco-editor [options]="editorOptions" formControlName="queryText" (init)="editorInit($event)"></ngx-monaco-editor>

Is there work around or its by design?

Thanks,
Oleg

Access to other available editor options

Thanks for the awesome work done with this module!
I'm interested in knowing if there's a particular reason for not passing an options object directly to Monaco, and instead exposing only a few parameters?

    language: string;
    lineNumbers?: boolean;
    theme?: string;
    readOnly?: boolean;
    scrollBeyondLastLine?: boolean;
    automaticLayout?: boolean;
    minimap?: any;

I guess that you probably didn't need it for your own project, but would it be possible to just pass all options through to Monaco and maybe expose the editor instance, so I can manually configure it myself (register a custom theme, language service etc.)?

Thanks,
Ivan

ngServe fails: Error in editor.api.d.ts

I've installed the editor as described in detail in the readme file. When I'm now trying to run Angular with the CLI command "ng serve", I get an error:

ERROR in node_modules/monaco-editor/esm/vs/editor/editor.api.d.ts(2167,44): error TS1005: ',' expected.
node_modules/monaco-editor/esm/vs/editor/editor.api.d.ts(2167,54): error TS1005: ',' expected.

For testing purposes I set up an empty angular project, ngx-monaco-editor is the only installed component. Am I doing something wrong here or is this a bug?

`css-element-queries` CommonJS or AMD dependency warning in fesm2015

Angular version: 10.1.0
ngx-monaco-editor version: 4.0.2

When I build my project in prod mode Angular displays the following warning:

WARNING in ...\node_modules\@materia-ui\ngx-monaco-editor\fesm2015\materia-ui-ngx-monaco-editor.js depends on 'css-element-queries'. CommonJS or AMD dependencies can cause optimization bailouts.
For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies

I can workaround it by adding the following to my angular.json:

{
  ...
  "projects": {
    "my-project": {
      ...
      "architect": {
        "build": {
          ...
          "options": {
            ...
            "allowedCommonJsDependencies": [
              "css-element-queries"
             ]
           }
        }
     }
   }
 }
}

But "css-element-queries" is totally unrelated to my app, so it would be great if I wouldn't need to add it to my angular.json.

Can't get materiaLoadMonacoEditor to work (trying to load Monaco from CDN)

I've tried this for over an hour and I just can't get it to work.

What I'm trying to do is get monaco from a CDN, so I don't have to distribute it with my application. So I need to set the root path, and from reading your code, I get the impression that I must simply add an attribute and put the value in that. I tried various versions of:

<ngx-monaco-editor [options]="editorOptions" [(ngModel)]="code"
materiaLoadMonacoEditor='https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.16.2/min/vs'></ngx-monaco-editor>

as well as versions of

  constructor(monacoConfig: MonacoEditorLoaderService) {
    monacoConfig.monacoPath = 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.16.2/min/vs';
   }

Neither work - i get errors or it doesn't do what I expect. Can you help?

Not binding [(ngModel)] cause error

I want to use this component like

<ngx-monaco-editor [options]="editorOptions" (init)="editorInit($event)" ></ngx-monaco-editor>

which there is no [(ngModel)] property. I will control the editor's content by directly accessing editor object:

editorInit(editor: monaco.editor.IStandaloneCodeEditor) {
    // get value via editor.getValue();
    // set value via editor.setValue();
    // I will also change editor's model later, so setting ngModel maybe hard for me
}

But this leads to many errors when interacting with editor:

ERROR Error: _this5.onTouched is not a function

TypeError: _this5.onTouched is not a function
    at monaco-editor.component.ts:194
    at l.fire (event.ts:576)
    at H.setValue (codeEditorWidget.ts:1609)
    at codeEditorWidget.ts:1405
    at l.fire (event.ts:576)
    at o._emitOugoingEvents (viewModelEventDispatcher.ts:62)
    at o.emitOutgoingEvent (viewModelEventDispatcher.ts:38)
    at w.setHasFocus (viewModelImpl.ts:179)
    at textAreaHandler.ts:307
    at l.fire (event.ts:576)
    at errors.ts:22
    at ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:28282)
    at ZoneDelegate.invokeTask (zone.js:420)
    at Zone.runTask (zone.js:188)
    at ZoneTask.invokeTask (zone.js:503)
    at ZoneTask.invoke (zone.js:492)
    at timer (zone.js:3034)

So is there any solution to solve this?

autocomplete is not working

Hello,

I need to provide auto-complete support for customerized language, see below:

onInit(editor) {
        this.editor = editor;
        this.editor._themeService.setTheme(this.theme);

        //here, we need to obtain monaco instance
        this.monaco = ((window as any).monaco);
        if (this.triggerAutoCompleteHook !== '') {
            this.monaco.languages.registerCompletionItemProvider('java', {
                provideCompletionItems: (model, position) => {
                    const textUntilPosition = model.getValueInRange(
                        {
                            startLineNumber: 1,
                            startColumn: 1,
                            endLineNumber: position.lineNumber,
                            endColumn: position.column
                        });
                    //obtaining the auto-complete term
                    const term = textUntilPosition.substr(textUntilPosition.lastIndexOf(this.triggerAutoCompleteHook) + 1);
                    return  this.codeEditorService.getAutoCompleteSuggestions(term);
                }
            });
        }

    }

But I do not see any suggestions popup there at all. I debugged code, the return command is already returning the suggestions.
Anything wrong here?
Thanks

editorOptions configuration problem

Version: "@materia-ui/ngx-monaco-editor": "^5.0.0" 、"monaco-editor": "^0.22.3"

Usage:
<ngx-monaco-editor fxFill #codeEditor [options]="editorOptions" [(ngModel)]="note.content" (init)="editorInit($event)" (keyup)="send()"> </ngx-monaco-editor>
editorOptions = { theme: 'vs-dark', language: 'markdown', minimap: { enabled: false, }, wordWrap: "on", };

Got the problem:

ERROR in src/main/webapp/app/note/note-editor/note-editor.component.html:182:59 - error TS2322: Type '{ theme: string; language: string; minimap: { enabled: boolean; }; wordWrap: string; }' is not assignable to type 'IStandaloneEditorConstructionOptions'.
Types of property 'wordWrap' are incompatible.
Type 'string' is not assignable to type '"on" | "off" | "wordWrapColumn" | "bounded" | undefined'.

182 <ngx-monaco-editor #codeEditor [options]="editorOptions" [(ngModel)]="note.content"

Thank you!!!

Unable to get a json schema used for validation

@GeoAstronaute

I cannot figure out how to get a custom json schema to be loaded in and used for validation purposes.

I have been following guides here https://levelup.gitconnected.com/autocomplete-json-with-angular-and-monaco-f1dcc01e36e1 and your readme of course.

Ctrl+Space just gives me the following $schema option and none of my schema defined properties.

enter image description here

I have clearly got something misconfigured and misunderstood how to set up the schema loading correctly.

Stackblitz of my setup - https://stackblitz.com/edit/materia-ngx-monaco-editor-example-y2tcrz?file=src/app/app.component.ts

Can you kindly point out what the problem is here, what am I doing incorrectly please?

Create more than one editor on the same page. Is it possible in this library ?

While creating more than one instance of the editor I am getting errors ->

Uncaught TypeError: Cannot set properties of undefined (setting 'browser')
at :1:46
at MonacoEditorLoaderService.push../node_modules/@materia-ui/ngx-monaco-editor/fesm5/materia-ui-ngx-monaco-editor.js.MonacoEditorLoaderService.addElectronFixScripts (materia-ui-ngx-monaco-editor.js:232)
at MonacoEditorLoaderService.push../node_modules/@materia-ui/ngx-monaco-editor/fesm5/materia-ui-ngx-monaco-editor.js.MonacoEditorLoaderService.loadMonaco (materia-ui-ngx-monaco-editor.js:203)
at new MonacoEditorLoaderService (materia-ui-ngx-monaco-editor.js:148)
at MonacoEditorLoaderService_Factory (materia-ui-ngx-monaco-editor.js:242)
at callFactory (core.js:20296)
at createProviderInstance (core.js:20254)
at resolveNgModuleDep (core.js:20229)
at NgModuleRef
.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef
.get (core.js:20905)
at resolveDep (core.js:21276)
(anonymous) @ VM2874:1
push../node_modules/@materia-ui/ngx-monaco-editor/fesm5/materia-ui-ngx-monaco-editor.js.MonacoEditorLoaderService.addElectronFixScripts @ materia-ui-ngx-monaco-editor.js:232
push../node_modules/@materia-ui/ngx-monaco-editor/fesm5/materia-ui-ngx-monaco-editor.js.MonacoEditorLoaderService.loadMonaco @ materia-ui-ngx-monaco-editor.js:203
MonacoEditorLoaderService @ materia-ui-ngx-monaco-editor.js:148
MonacoEditorLoaderService_Factory @ materia-ui-ngx-monaco-editor.js:242
callFactory @ core.js:20296
createProviderInstance @ core.js:20254
resolveNgModuleDep @ core.js:20229
push../node_modules/@angular/core/fesm5/core.js.NgModuleRef
.get @ core.js:20905
resolveDep @ core.js:21276
createClass @ core.js:21148
createDirectiveInstance @ core.js:21027
createViewNodes @ core.js:29387
createEmbeddedView @ core.js:29295
callWithDebugContext @ core.js:30309
debugCreateEmbeddedView @ core.js:29833
push../node_modules/@angular/core/fesm5/core.js.TemplateRef
.createEmbeddedView @ core.js:20742
push../node_modules/@angular/core/fesm5/core.js.ViewContainerRef_.createEmbeddedView @ core.js:20608
push../node_modules/@angular/common/fesm5/common.js.NgIf.updateView @ common.js:4018
set @ common.js:3980
updateProp @ core.js:21303
checkAndUpdateDirectiveInline @ core.js:21054
checkAndUpdateNodeInline @ core.js:29495
checkAndUpdateNode @ core.js:29457
debugCheckAndUpdateNode @ core.js:30091
debugCheckDirectivesFn @ core.js:30051
eval @ FrontendEditorComponent.html:7
debugUpdateDirectives @ core.js:30043
checkAndUpdateView @ core.js:29439
callViewAction @ core.js:29680
execEmbeddedViewsAction @ core.js:29643
checkAndUpdateView @ core.js:29440
callViewAction @ core.js:29680
execEmbeddedViewsAction @ core.js:29643
checkAndUpdateView @ core.js:29440
callViewAction @ core.js:29680
execComponentViewsAction @ core.js:29622
checkAndUpdateView @ core.js:29445
callViewAction @ core.js:29680
execEmbeddedViewsAction @ core.js:29643
checkAndUpdateView @ core.js:29440
callViewAction @ core.js:29680
execEmbeddedViewsAction @ core.js:29643
checkAndUpdateView @ core.js:29440
callViewAction @ core.js:29680
execEmbeddedViewsAction @ core.js:29643
checkAndUpdateView @ core.js:29440
callViewAction @ core.js:29680
execComponentViewsAction @ core.js:29622
checkAndUpdateView @ core.js:29445
callViewAction @ core.js:29680
execEmbeddedViewsAction @ core.js:29643
checkAndUpdateView @ core.js:29440
callViewAction @ core.js:29680
execEmbeddedViewsAction @ core.js:29643
checkAndUpdateView @ core.js:29440
callViewAction @ core.js:29680
execEmbeddedViewsAction @ core.js:29643
checkAndUpdateView @ core.js:29440
callViewAction @ core.js:29680
execComponentViewsAction @ core.js:29622
checkAndUpdateView @ core.js:29445
callViewAction @ core.js:29680
execEmbeddedViewsAction @ core.js:29643
checkAndUpdateView @ core.js:29440
callViewAction @ core.js:29680
execComponentViewsAction @ core.js:29622
checkAndUpdateView @ core.js:29445
callWithDebugContext @ core.js:30309
debugCheckAndUpdateView @ core.js:30011
push../node_modules/@angular/core/fesm5/core.js.ViewRef
.detectChanges @ core.js:20686
push../node_modules/@angular/core/fesm5/core.js.ApplicationRef.tick @ core.js:27109
(anonymous) @ core.js:26998
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
onInvoke @ core.js:26256
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:390
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:150
push../node_modules/@angular/core/fesm5/core.js.NgZone.run @ core.js:26170
next @ core.js:26998
schedulerFn @ core.js:23735
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:192
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:130
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:76
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:53
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:23719
checkStable @ core.js:26225
onLeave @ core.js:26292
onInvokeTask @ core.js:26250
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:422
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:195
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:498
invokeTask @ zone.js:1693
globalZoneAwareCallback @ zone.js:1719
Show 64 more frames
loader.js:1261 Duplicate definition of module 'vscode-languageserver-types/main'
s.defineModule @ loader.js:1261
o @ loader.js:1713
(anonymous) @ cssMode.js:7
(anonymous) @ cssMode.js:7
loader.js:1261 Duplicate definition of module 'vscode-languageserver-types'
s.defineModule @ loader.js:1261
o @ loader.js:1713
(anonymous) @ cssMode.js:7
3core.js:4002 ERROR Error: _this.onErrorStatusChange is not a function

TypeError: _this.onErrorStatusChange is not a function
at materia-ui-ngx-monaco-editor.js:502
at e.fire (event.ts:563)
at codeEditorWidget.ts:1247
at e.fire (event.ts:563)
at t.endDeferredEmit (textModel.ts:2683)
at o.pushEditOperations (textModel.ts:1034)
at t.executeEdits (cursor.ts:633)
at t.executeEdits (codeEditorWidget.ts:993)
at firepad.min.js:1
at Array.forEach ()
at errors.ts:22
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Object.onInvokeTask (core.js:26247)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask (zone.js:498)
at ZoneTask.invoke (zone.js:487)
at timer (zone.js:3070)
editor

Cannot set property 'browser' of undefined

Hello,

I configured the editor and it works as expected, but I get this error in console:

Uncaught TypeError: Cannot set property 'browser' of undefined
    at <anonymous>:1:46
    at MonacoEditorLoaderService.addElectronFixScripts (materia-ui-ngx-monaco-editor.js:80)
    at MonacoEditorLoaderService.loadMonaco (materia-ui-ngx-monaco-editor.js:63)
    at new MonacoEditorLoaderService (materia-ui-ngx-monaco-editor.js:29)
    at Object.MonacoEditorLoaderService_Factory [as factory] (materia-ui-ngx-monaco-editor.js:88)
    at R3Injector.hydrate (core.js:11412)
    at R3Injector.get (core.js:11232)
    at NgModuleRef$1.get (core.js:25325)
    at R3Injector.get (core.js:11243)
    at NgModuleRef$1.get (core.js:25325)

Thanks!

monaco-editor update to 0.21.2

Hi! It would be nice to access monaco-editor 0.21.2. This is 7 months of updates, including top-level await.

Thanks in advance!

Help please: how can we show the syntax error, highlight error in editor?

Hello,
We have a requirement to have auto checking for syntax error, may I ask if this is supported by this angular library?

For example, I am using it to provide sql support, and if I typed in

wrong_select * form field

I want the wrong_select to be indicated as wrong. and if I mouse hovering, suggestion for fix will appear.

Can I have any example on how to enable the syntax error checking?

I checked monaco github, they support it like this:

microsoft/monaco-editor#1477
Using setModelMarkers

But I do not know how to use that solution in this angular plugin.

Can anyone help here?

Thanks in advance.

Error loading monaco-editor

I install this package on the https://github.com/maximegris/angular-electron template and throw this:

materia-ui-ngx-monaco-editor.js:54 Error loading monaco-editor:  Error: Invalid package /Users/savila/work/angular-electron/node_modules/electron/dist/Electron.app/Contents/Resources/electron.asar
    at createError (electron/js2c/asar_bundle.js:5)
    at fsReadFileAsar (electron/js2c/asar_bundle.js:5)
    at Object.e.readFile (electron/js2c/asar_bundle.js:5)
    at r._readSourceAndCachedData (loader.js:958)
    at r.load (loader.js:838)
    at r.load (loader.js:614)
    at l (loader.js:1635)
    at r._loadModule (loader.js:1647)
    at r._resolve (loader.js:1732)
    at r.defineModule (loader.js:1379)

Unable to get monaco instance loading in test framework - Karma

Hello again @GeoAstronaute!

I am having trouble getting the monaco global to be recognised during unit test runs with Karma+Jasmine.

Here is a replicable demo -
https://stackblitz.com/edit/materia-ngx-monaco-editor-ng9-testing-fun?file=src/main.ts

Please note that I am trying to get this to work via loading in the monaco-editor using the assets entry in the angular.json file and not via a MONACO_PATH provider to a CDN in the app module - e.g.

{
   "glob": "**/*",
   "input": "node_modules/monaco-editor",
   "output": "assets/monaco-editor/"
}

In the demo app, you can switch between running the app or the tests by commenting\un-commenting the relevant sections in the main.ts file.

The app itself does not actually load the editor, I think its something to do with stackblitz not able to resolve the node_modules path in the asset glob pattern in the angular.json file as when im running this for real in my actual application locally it works fine.

Changing the stackblitz to use the MONACO_PATH provider approach via CDN, does as expected load up the editor fine when running the app. BUT, the tests still fails where it cannot find the monaco instance.

See here - https://stackblitz.com/edit/materia-ngx-monaco-editor-ng9-tests-cdn?file=src/app/app.component.ts

Have you got any suggestions about how I can get this library (or monaco-editor more specifically) to play nicely with the testing framework?

Use monaco-editor as peer dependency

Not sure if this would be possible here, but similar libraries (ng-monaco-editor, ngx-monaco-editor) use monaco-editor as a peer dependency to allow independently updating the monaco-editor package. This makes sense as it seems monaco-editor package rarely (if ever) releases breaking changes that will break a wrapper package like this.

Angular 13 support

While updating Angular to v13, I got these errors:

npm ERR! While resolving: [email protected]
npm ERR! Found: @angular/[email protected]
npm ERR! node_modules/@angular/common
npm ERR!   @angular/common@"~13.0.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"9.x || 10.x || 11.x || 12.x" from @materia-ui/[email protected]
npm ERR! node_modules/@materia-ui/ngx-monaco-editor
npm ERR!   @materia-ui/ngx-monaco-editor@"5.1.0" from the root project

Seems that a "13.x" peerDependencies is required.

Also, add support for RxJS 7 (defaulted in Angular 13) if available. Thanks!

Change Editor Language Dynamically

Hi,

I've an editor like this -

<ngx-monaco-editor #monacoEditor style="height: 100%;" (init)="onInit($event)" [options]="editorOptions"
                       (ngModelChange)="this.candidateDocument.save()" [(ngModel)]="getData().candidateData">
    </ngx-monaco-editor>

I want to change the language of the monaco editor dynamically. Things I've tried -

app.component.ts:

  @ViewChild('monacoEditor') monacoEditor;
  ....

  changeLanguage() {
    this.monacoEditor.options.language = 'plaintext'; // doesn't work.
  }

app.component.ts:

  private editor: MonacoStandaloneCodeEditor = null;

  onInit(editor: MonacoStandaloneCodeEditor) {
    this.editor = editor;
  }
  ...

  changeLanguage() {
    this.editorOptions.language = 'plaintext';
    this.editor.updateOptions(this.editorOptions); // doesn't work
 }

Could you please help me changing the language dynamically? Thank you.

How to use all pre-installed languages?

I use Angular + Electron. Editor works, but only for js/ts, html and css. How to use other languages as well? I tried to use Editor options, but the result is unformatted text if I pass whatever language except mentioned ones.
i.e.
this one gives right format
editorOptions = {theme: 'vs-dark', language: 'javascript'};
this one gives white text
editorOptions = {theme: 'vs-dark', language: 'java'};

Monaco Editor Not Initializing In Electron With Angular 11 (Reproduction Link in Description)

Reproduced Here: https://github.com/stagefright5/strong-soap-dynamic-module-load-issue/tree/issue-monaco-load

This repo tries to create the official demo inside the electron.

In the above repo inside monaco.component.html, there is an event listener for the init event that is supposed to be emitted by the ngx-monaco-editor. That listener is never run because init is never emitted.

Please take a look at this and confirm if this is an issue.

Move cursor to a specific position

I've a multi-user ngx-monaco-editor (with firebase real-time sync, similar to firepad.io), i.e. multiple users can simultaneously make changes, and the changes will be propagated to every other user. This is how my ngx-monaco-editor is setup:

    <ngx-monaco-editor #editor [options]="editorOptions" (onInit)="onEditorInit($event)"
                       (ngModelChange)="this.model.candidateDocument.save()" [(ngModel)]="getData().candidateData">

Now as soon as ngModel change event is emitted, monaco-editor content is updated. Great!!

The problem I face is with cursor. As soon as the editor content is updated, the cursor moves to 1st line, position 0. Complete reset.

I want to avoid it. Is there a way to,

(i) Keep the cursor at the same place when the ngx-monaco-editor content is updated dynamically?
OR (ii) If not possible, my only option will be to manually keep track of the cursor, and update its position on every change. However, for that, I'll need access to (a) current curser position, and (b) a way to set cursor position dynamically. I wonder if that's possible.

Could you please help me understand how to achieve this? Feel free to ask for any clarification. Thanks a lot.

Not works in electron

Hi
I try to load the editor with local path (default or explicit) in ELECTRON but it wont work.
any idea ?

Using this setup

 "assets": [
         ....
        { "glob": "**/*", "input": "node_modules/monaco-editor", "output": "assets/monaco-editor/" }
  ],

CDN
WORKS IN BROWSER
WORKS IN ELECTRON

    ....
    MonacoEditorModule,
    ...
  ],
  providers: [
    {
       provide: MONACO_PATH,
       useValue: 'https://unpkg.com/[email protected]/min/vs'
     }
  ],

loader.js LOAD
editor.main.js LOAD
editor.main.css LOAD
editor.main.nls.js LOAD
workerMain.js LOAD

LOCAL
WORKS IN BROWSER
NOT WORK IN ELECTRON

    ....
    MonacoEditorModule,
    ...
  ],
  providers: [],

loader.js LOAD
editor.main.js NOT LOAD
editor.main.css NOT LOAD
editor.main.nls.js NOT LOAD
workerMain.js NOT LOAD

package.json

@angular/animations": "^8.2.14",
    "@angular/cdk": "^8.2.3",
    "@angular/cdk-experimental": "^8.2.3",
    "@angular/common": "~8.2.14",
    "@angular/compiler": "~8.2.14",
    "@angular/core": "~8.2.14",
    "@angular/forms": "~8.2.14",
    "@angular/material": "^8.2.3",
    "@angular/platform-browser": "~8.2.14",
    "@angular/platform-browser-dynamic": "~8.2.14",
    "@angular/router": "~8.2.14",
    "@materia-ui/ngx-monaco-editor": "^4.0.2",
    ...
    "monaco-editor": "^0.21.2",
    ...

Enable to specify document uri

Hi,

To be able to use document uri, it can be neat to be able to pass in options the uri of the document.
Typically it enables to have implicit schema validation and completion without having to match any document (*) or bet on "inmemory://model/1" implicit uri.

See microsoft/monaco-editor#191 for details.

Romain

Please add a license file

Buried in /docs/3rdpartylicenses.txt I see that this is meant to be MIT licensed. It would be helpful to have this more clearly stated in a LICENSE file in the root and in the package.json.

Unable to force layout recalculation of editor inside a tab panel component

I am struggling with an instance of ngx-monaco-editor inside a primeng tab panel which seems to 'lose' its size calculations when switching to another tab, changing the model value bound to the editor and then switching back to the initial tab again.

https://stackblitz.com/edit/primeng9-tabs-monaco-editor

Steps to replicate using url above:

  • The 'Editor' tab will be initially selected
  • Select 'Tab 2'
  • Click the 'change code' button
  • Change back to the 'Editor' tab and now see that the editor has shrunk in size

Before:

enter image description here

After:

enter image description here

Inspecting in the dom, the originally assigned style is still present.

As you can see from the source code in my sample app, I also tried using the editor's layout method in the tab change event to attempt to force a recalculation of the size based on the container but this has made no difference

Remove Find widget over Internet Explorer

I want to use @materia-ui/ngx-monaco-editor in my project. While creating a POC, I found that the find and auto-suggestion functionalities are not working on IE while the same code works for chrome. I have handled the auto-suggestion by checking browser. But not able to fix the find widget issue.
I want to either fix this issue in IE or remove the widget in IE. Please help me with this.
Thanks in advance !

chrome
IE

Angular Ivy

Is the library already compatible with angular ivy?

Angular: 8.2.14 - error TS1086: An accessor cannot be declared in an ambient context.

Hi,

first of all - Thank you for your work!

I created a new Angular 8 project with the current newest version and installed your package.
I can´t start the Angular App with ng serve. I got the following expection:

---------------- 8< -------------------------
ng serve
10% building 3/3 modules 0 activei 「wds」: Project is running at http://localhost:4200/webpack-dev-server/
i 「wds」: webpack output is served from /
i 「wds」: 404s will fallback to //index.html

chunk {main} main.js, main.js.map (main) 2.05 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 122 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 9.74 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 340 kB [initial] [rendered]
Date: 2019-12-21T12:18:05.135Z - Hash: 9a1992aed70d1fd9e5f3 - Time: 11071ms

ERROR in node_modules/monaco-editor/esm/vs/editor/editor.api.d.ts:50:9 - error TS1086: An accessor cannot be declared in an ambient context.

50 get token(): CancellationToken;
~~~~~
node_modules/monaco-editor/esm/vs/editor/editor.api.d.ts:125:9 - error TS1086: An accessor cannot be declared in an ambient context.

125 get fsPath(): string;
~~~~~~

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
i 「wdm」: Failed to compile.

---------------- >8 -------------------------

Do you have an idea for the solution?

Object(...) is not a function

image

enviroment:
"@angular/animations": "~7.2.0",
"@angular/common": "~7.2.0",
"@angular/compiler": "~7.2.0",
"@angular/core": "~7.2.0",
"@angular/forms": "~7.2.0",
"@angular/platform-browser": "~7.2.0",
"@angular/platform-browser-dynamic": "~7.2.0",
"@angular/router": "~7.2.0",
"@materia-ui/ngx-monaco-editor": "^4.0.1",
"classlist.js": "^1.1.20150312",
"core-js": "^2.5.4",
"element-resize-event": "^3.0.3",
"monaco-editor": "^0.15.6",
"ng-zorro-antd": "^7.5.1",
"ng2-cookies": "^1.0.12",
"rxjs": "~6.3.3",
"tslib": "^1.9.0",
"typescript": "^3.2.4",
"url-search-params-polyfill": "^5.0.0",
"web-animations-js": "^2.3.1",
"zone.js": "~0.8.26"

ERROR: 'MonacoEnvironment' was also declared here.

Error: node_modules/monaco-editor/esm/vs/editor/editor.api.d.ts:12:9 - error TS2451: Cannot redeclare block-scoped variable 'MonacoEnvironment'.

12     let MonacoEnvironment: Environment | undefined;
           ~~~~~~~~~~~~~~~~~

  node_modules/@materia-ui/ngx-monaco-editor/lib/interfaces/monaco.d.ts:11:13
    11 declare let MonacoEnvironment: monaco.Environment | undefined;
                   ~~~~~~~~~~~~~~~~~
    'MonacoEnvironment' was also declared here.
node_modules/@materia-ui/ngx-monaco-editor/lib/interfaces/monaco.d.ts:11:13 - error TS2451: Cannot redeclare block-scoped variable 'MonacoEnvironment'.

11 declare let MonacoEnvironment: monaco.Environment | undefined;
               ~~~~~~~~~~~~~~~~~

  node_modules/monaco-editor/esm/vs/editor/editor.api.d.ts:12:9
    12     let MonacoEnvironment: Environment | undefined;
               ~~~~~~~~~~~~~~~~~
    'MonacoEnvironment' was also declared here.

I'm using versions:

"@materia-ui/ngx-monaco-editor": "^5.0.0-beta.0",
"monaco-editor": "^0.21.2"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.