Code Monkey home page Code Monkey logo

ngx-monaco-editor's Introduction

Monaco Editor Component for Angular 2 and above.

  • Angular <= 4: v3.x.x
  • Angular 5: v5.x.x
  • Angular 6: v6.x.x
  • Angular 7: v7.x.x
  • Angular 8: v8.x.x
  • Angular 9: v9.x.x
  • Angular 10: v10.x.x
  • Angular 12: v12.x.x

Using this Module you can utilize the Monaco Editor as an Angular Component. Feel free to contribute, raise feature requests and make it better.

Supports all the options available in monaco-editor Monaco Editor Options

Setup

Installation

Install from npm repository:

npm install monaco-editor ngx-monaco-editor --save

For angular version 6 use v6.x.x

npm install [email protected] --save

Add the glob to assets in .angular-cli.json schema - projects.[project-name].architect.build (to make monaco-editor lib available to the app):

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

For Angular 6 and below, add the glob to assets in angular.json

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

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 'ngx-monaco-editor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    MonacoEditorModule.forRoot() // use forRoot() in main app module only.
  ],
  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}';
}

Include editor in html with options and ngModel bindings.(eg: app.component.html)

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

Include diff-editor in html with options.(eg: app.component.html)

<ngx-monaco-diff-editor [options]="options" [originalModel]="originalModel" [modifiedModel]="modifiedModel"></ngx-monaco-diff-editor>
import { Component } from '@angular/core';
import { DiffEditorModel } from 'ngx-monaco-editor';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  options = {
    theme: 'vs-dark'
  };
  originalModel: DiffEditorModel = {
    code: 'heLLo world!',
    language: 'text/plain'
  };

  modifiedModel: DiffEditorModel = {
    code: 'hello orlando!',
    language: 'text/plain'
  };
}

Styling

To match height of container element add height: 100% and wrap in container

<div style="height: 500px">
    <ngx-monaco-editor style="height: 100%" [options]="editorOptions" [(ngModel)]="code"></ngx-monaco-editor>
</div>

Add class to editor tag. (eg. class="my-code-editor")

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

Add styling in css/scss file:

.my-code-editor {
  .editor-container {
    height: calc(100vh - 100px);
  }
}

Set automaticLayout option to adjust editor size dynamically. Recommended when using in modal dialog or tabs where editor is not visible initially.

Events

Output event (onInit) expose editor instance that can be used for performing custom operations on the editor.

<ngx-monaco-editor [options]="editorOptions" [(ngModel)]="code" (onInit)="onInit($event)"></ngx-monaco-editor>
export class AppComponent {
  editorOptions = {theme: 'vs-dark', language: 'javascript'};
  code: string= 'function x() {\nconsole.log("Hello world!");\n}';
  onInit(editor) {
      let line = editor.getPosition();
      console.log(line);
    }
}

Configurations

forRoot() method of MonacoEditorModule accepts config of type NgxMonacoEditorConfig.

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

import { MonacoEditorModule, NgxMonacoEditorConfig } from 'ngx-monaco-editor';
import { AppComponent } from './app.component';

const monacoConfig: NgxMonacoEditorConfig = {
  baseUrl: 'app-name/assets', // configure base path cotaining monaco-editor directory after build default: './assets'
  defaultOptions: { scrollBeyondLastLine: false }, // pass default options to be used
  onMonacoLoad: () => { console.log((<any>window).monaco); } // here monaco object will be available as window.monaco use this function to extend monaco editor functionalities.
};

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

Configure JSON Defaults

onMonacoLoad property of NgxMonacoEditorConfig can be used to configure JSON default.

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

import { MonacoEditorModule, NgxMonacoEditorConfig } from 'ngx-monaco-editor';
import { AppComponent } from './app.component';

export function onMonacoLoad() {

  console.log((window as any).monaco);

  const uri = monaco.Uri.parse('a://b/foo.json');
  monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
    validate: true,
    schemas: [{
      uri: 'http://myserver/foo-schema.json',
      fileMatch: [uri.toString()],
      schema: {
        type: 'object',
        properties: {
          p1: {
            enum: ['v1', 'v2']
          },
          p2: {
            $ref: 'http://myserver/bar-schema.json'
          }
        }
      }
    }, {
      uri: 'http://myserver/bar-schema.json',
      fileMatch: [uri.toString()],
      schema: {
        type: 'object',
        properties: {
          q1: {
            enum: ['x1', 'x2']
          }
        }
      }
    }]
  });

}

const monacoConfig: NgxMonacoEditorConfig = {
  baseUrl: 'assets',
  defaultOptions: { scrollBeyondLastLine: false },
  onMonacoLoad
};

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

Now pass model config of type NgxEditorModel to Editor Component

@Component({
  selector: 'app-root',
  template: `<ngx-monaco-editor [options]="options" [model]="model"></ngx-monaco-editor>`,
  styles: []
})
export class AppComponent {
  options = {
    theme: 'vs-dark'
  };
  
  jsonCode = [
    '{',
    '    "p1": "v3",',
    '    "p2": false',
    '}'
  ].join('\n');

  model: NgxEditorModel = {
    value: this.jsonCode,
    language: 'json',
    uri: monaco.Uri.parse('a://b/foo.json')
  };
}

Links

Monaco Editor
Monaco Editor Options

License

MIT © Atul Kumar

ngx-monaco-editor's People

Contributors

atu1kr avatar darinw avatar gzamb avatar humberd avatar ialexivy avatar zvonimirfras 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ngx-monaco-editor's Issues

ngx-monaco-editor component requires options unnecessarily

Thanks to your handy defaultOptions feature, I can ensure consistency in the presentation of the monaco editor throughout my app without specifying options. However, whenever I remove "options" from component implementation, e.g.
<ngx-monaco-editor [model]="model"></ngx-monaco-editor>

I get the exception:

TypeError: Cannot set property 'model' of undefined
    at EditorComponent.set [as model] (editor.component.js:42)
    at updateProp (core.js:12619)
    at checkAndUpdateDirectiveInline (core.js:12326)
    at checkAndUpdateNodeInline (core.js:13893)
    at checkAndUpdateNode (core.js:13836)
    at debugCheckAndUpdateNode (core.js:14729)
    at debugCheckDirectivesFn (core.js:14670)
    at Object.eval [as updateDirectives] (EditContentComponent.html:37)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:14655)
    at checkAndUpdateView (core.js:13802)

Which points to this line in editor.component:
this.options.model = model;

As a result, I am forced to use the editor component as follows:
<ngx-monaco-editor [options]="{}" [model]="model"></ngx-monaco-editor>

It doesn't make sense to me that I would need to specify options. It seems like the responsibility of the component to provide a default if one is not provided, especially since the module essentially makes this directive unnecessary.

Thanks for what you've done here! I appreciate it!

Not able to build my project after introducing ngx-monaco-editor

I'm able to make monaco editor work using ng serve even though it gives me an error message. It complies after subsequent file edits.

The build fails with the same error message.

Here is the output

ERROR in Metadata version mismatch for module /Code/application/node_modules/ngx-monaco-editor/editor.module.d.ts, found version 4, expected 3

ERROR in ./src/main.ts
Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in '/Code/application/src'
 @ ./src/main.ts 4:0-74
 @ multi ./src/main.ts

I updated my angular cli from 1.0.3 to 1.6 and its not building there as well. But I get a slightly different error.

ERROR in Error: Metadata version mismatch for module /Code/debug/node_modules/ngx-monaco-editor/index.d.ts, found version 4, expected 3, resolving symbol AppModule in /Code/debug/src/app/app.module.ts, resolving symbol AppModule in /Code/debug/src/app/app.module.ts
    at syntaxError (/Code/debug/node_modules/@angular/compiler/bundles/compiler.umd.js:1724:34)
    at simplifyInContext (/Code/debug/node_modules/@angular/compiler/bundles/compiler.umd.js:24854:23)
    at StaticReflector.simplify (/Code/debug/node_modules/@angular/compiler/bundles/compiler.umd.js:24866:13)
    at StaticReflector.annotations (/Code/debug/node_modules/@angular/compiler/bundles/compiler.umd.js:24314:41)
    at _getNgModuleMetadata (/Code/debug/node_modules/@angular/compiler-cli/src/ngtools_impl.js:138:31)
    at _extractLazyRoutesFromStaticModule (/Code/debug/node_modules/@angular/compiler-cli/src/ngtools_impl.js:109:26)
    at Object.listLazyRoutesOfModule (/Code/debug/node_modules/@angular/compiler-cli/src/ngtools_impl.js:53:22)
    at Function.NgTools_InternalApi_NG_2.listLazyRoutes (/Code/debug/node_modules/@angular/compiler-cli/src/ngtools_api.js:91:39)
    at AotPlugin._getLazyRoutesFromNgtools (/Code/debug/node_modules/@ngtools/webpack/src/plugin.js:241:66)
    at _donePromise.Promise.resolve.then.then.then.then.then (/Code/debug/node_modules/@ngtools/webpack/src/plugin.js:495:24)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:169:7)

I looked at similar errors in other repos on google, and it seems like its because of differences in Angular 5 and Angular 4.. like for example this issue angular/components#8229

How do I fix this?
Thank you.

how to create a new theme

can you please tell me how to create this themes in monaco ?

monaco.editor.defineTheme('myTheme', {
base: 'vs',
inherit: true,
rules: [{ background: 'EDF9FA' }],
colors: {
'editor.foreground': '#000000',
'editor.background': '#EDF9FA',
'editorCursor.foreground': '#8B0000',
'editor.lineHighlightBackground': '#0000FF20',
'editorLineNumber.foreground': '#008800',
'editor.selectionBackground': '#88000030',
'editor.inactiveSelectionBackground': '#88000015'
}
});

here is the code that I took from monaco playground. I will be glad if you give me a solution.

ngx-monaco-editor not working with angular 6

ngx-monaco-editor not working with angular 6 and angular cli-6 getting below error

Refused to execute script from 'http://localhost:8425/dashboard/assets/monaco/vs/loader.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

I am using "ngx-monaco-editor": "^6.0.0". With angular 5 and mgx-monaco-editor 4 I am not facing any issues.

ngx-monaco-editor is showing no Suggestions

Cloned this project & customizing the same - Word Suggestions are coming only for Css & JavaScript languages as they are default.But requirement is Java,Csharp editors.

Html code -

<ngx-monaco-editor [options]="options" [(ngModel)]="displaycode" (onInit)="onInit($event)"></ngx-monaco-editor>

TypeScript code -

options = {theme: 'vs-dark'};
onInit(editor) {
  this.editor = editor;
}

I tried

1) options = {theme: 'vs',quickSuggestions: true,wordBasedSuggestions: true};

2) Inside ngOnInit function:

this.options = Object.assign({}, this.options, {theme: 'vs',language: java});
Theme changes are reflecting & if i debug language is updated in options.

3)  updateOptions() {
     this.toggleLanguage = !this.toggleLanguage;
     if (this.toggleLanguage) {
           this.code = this.javaCode;
           this.options = Object.assign({}, this.options, { language: 'java' });
     } else {
          this.code = this.cSharpCode;
          this.options = Object.assign({}, this.options, { language: 'csharp' });
     }

Image of editor showing - no Suggestions

i went through github links like microsoft/monaco-editor#632, but didn't find any help

How can i get word Suggestion working in the editor for Java & cSharp ?
Thanks in advance.

Angular 5

I know angular 5 just came out. Is there a plan to upgrade to it?

Diff editor doesn't update on model change

When using the diff editor and updating originalModel and modifiedModel editor view doesn't update, i think the issue is that the model only created when editor init for the first time, instead it should probably create new model each time that input values changes, OnChanges event.

`<ngx-monaco-diff-editor [options]="options" [originalModel]="originalModel" [modifiedModel]="modifiedModel">

updateView(){
this.originalModel.code='Update';
this.modifiedModel.code='Update';
}`

Electron Support ?

The Editor is working fine in Web.
But running it in Electron the Editor is not loading and I get the error:

window.require.config is not a function

It is from here:

 var onGotAmdLoader = function () {
                    // Load monaco
                    window.require.config({ paths: { 'vs': baseUrl + "/monaco/vs" } });
                    window.require(['vs/editor/editor.main'], function () {
                        if (typeof _this.config.onMonacoLoad === 'function') {
                            _this.config.onMonacoLoad();
                        }
                        _this.initMonaco(_this.options);
                        resolve();
                    });
                };

YAML Support

Hi @atul-wizni ,

Thanks for this component. it is really helping me in my project.
I would like to know how we can support YAML file in this editor ?
If yes, will it show syntax errors as well ?
What configuration we will be required to change.

Appreciate your help on this.

Doc. correction. To use 'ngModel' you need FormsModule imported

Pl. add this code to reademe file , could save some time for first time users. Tx.

`import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';
import { MonacoEditorModule } from 'ngx-monaco-editor';

import { AppComponent } from './app.component';

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

ERROR TypeError: Cannot read property 'config' of undefined

传入自定义baseUrl 的config 报错 Cannot read property 'config' of undefined

报错信息
image

node-modules 中相关的错误文件是

                var onGotAmdLoader = function () {
                    // Load monaco
                    window.require.config({ paths: { 'vs': baseUrl + "/monaco/vs" } });
                    window.require(['vs/editor/editor.main'], function () {
                        if (typeof _this.config.onMonacoLoad === 'function') {
                            _this.config.onMonacoLoad();
                        }
                        _this.initMonaco(_this.options);
                        resolve();
                    });
                };

angular版本相关信息

Angular CLI: 1.6.1
Node: 9.2.0
OS: darwin x64
Angular: 5.1.1
@angular/cdk: 5.0.1
@angular/cli: 1.6.1
@angular-devkit/build-optimizer: 0.0.36
@angular-devkit/core: 0.0.22
@angular-devkit/schematics: 0.0.42
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.1
@schematics/angular: 0.1.11
@schematics/schematics: 0.0.11
typescript: 2.5.3
webpack-bundle-analyzer: 2.9.1
webpack: 3.10.0

ngx-monaco-editor版本 "ngx-monaco-editor": "^4.0.1",

使用代码

import { MonacoEditorModule, NgxMonacoEditorConfig } from 'ngx-monaco-editor';

const monacoConfig: NgxMonacoEditorConfig = {
    baseUrl: '/#/test/saas', // configure base path for monaco editor
    defaultOptions: { scrollBeyondLastLine: false }, // pass deafult options to be used
    onMonacoLoad: () => { console.log((<any>window).monaco); } // here monaco object will be avilable as window.monaco use this function to extend monaco editor functionalities.
  };

@NgModule({
    imports: [
        SharedModule,
        RouterModule.forRoot(routes, { useHash: true }),
        QRCodeModule,
        NgxEchartsModule,
        MonacoEditorModule.forRoot(monacoConfig),
    ],

请问下这个是什么错误导致的

Monaco editor does not work in angular tab

I am using Monaco editor with angular 1.6, In my UI I have different tabs(as in [this][1] example) pointing to different html page.

[1]: https://www.w3schools.com/howto/howto_js_tabs.asp I am using Monaco editor, but the problem is it is getting applied(integrated) to the items(text/textbox) only the first tab , if I apply in in other tab other than the first it is not showing up there , this is the bit of my code just to get an idea.

angular.module('sample').config(['$routeProvider', function ($routeProvider) {
  $routeProvider.when('/', {
    templateUrl: '/',
    controller: 'MainCtrl'
  }).when('/sample1', {
    templateUrl: '/sample1',
    controller: 'sample1Ctrl'
  }).when('/sample2', {
    templateUrl: '/sample2',
    controller: 'sample2Ctrl',
  }).when('/sample3', {
    templateUrl: '/sample3',
    controller: 'sample3Ctrl'
  }).when('/sample4', {
    templateUrl: '/sample4',
    controller: 'sample4Ctrl'
  }).otherwise({
    redirectTo: '/'
  });
}]);    
angular.module('sample').controller('TabCtrl', function ($scope) {
      $scope.tabs = [
        {
          slug: 'sample1',
          title: "Register sample1",
          content: "sample1"
        },{
          slug: 'sample2',
          title: "Register sample2",
          content: 'sample2'
        },
        {
          slug: 'sample3',
          title: "Get sample3",
          content: "sample3"
        },
        {
          slug: 'sample4',
          title: "Register sample4",
          content: "sample4"
        }
      ];
    });

this is how I am using Monaco editor in the controller

$scope.experimentConfigEditor = monaco.editor.create(document.getElementById('experimentText'), {
    value: '',
    language: 'json',
    minimap: {
      enabled: false
    }
  });
  $scope.newExperimentConfigEditor = monaco.editor.create(document.getElementById('newExperimentText'), {
    value: '',
    language: 'json',
    minimap: {
      enabled: false
    }
  });
  $scope.getConfigFromDatalensTextEditor = monaco.editor.create(document.getElementById('getText'), {
    value: '',
    language: 'json',
    minimap: {
      enabled: false
    }
  });

and this is the sample html file

<div id="experimentText" name="experimentText" style="width:600px;height:200px;border:1px solid grey" ng-show="experimentText" ng-model="formData. experimentText"></div>
So If I use the controller with Monaco in the first tab then only Monaco is getting applied otherwise it's not working the, html elements are coming as an simple elements without Monaco editor in UI.

Support base-href option

ngx-monaco-editor does not take into account base-href option when building Angular app. For now, we have to configure baseUrl when importing the module. I think the component should be able to get the baseHref and use it as default path. Meaning, we should perhaps have by default ${baseHref}/assets instead of /assets.

const baseUrl = this.config.baseUrl || '/assets';

To do so, we first have to inject the baseHref, which is not a simple thing to do 😛 (at least elegantly). My idea is to first extract a service from the BaseEditor class and then manage to inject the baseHref. What do you think?
ps: For instance, I use a hacky way to do this behaviour without altering the code in my project https://github.com/yowari/code-challenger/blob/master/src/app/shared/shared.module.ts
btw: first time trying to contribute to a GitHub project so please be kind 😊

Can't bind to ngModel

I'm getting the following error at runtime:

Uncaught Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'ngx-monaco-editor'.
1. If 'ngx-monaco-editor' is an Angular component and it has 'ngModel' input, then verify that it is part of this module.
2. If 'ngx-monaco-editor' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
	</div>

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

	<!--The content below is only a placeholder and can be repl"): ng:///AppModule/AppComponent.html@10:46
    at syntaxError (compiler.js:466)
    at TemplateParser.parse (compiler.js:24329)
    at JitCompiler._parseTemplate (compiler.js:33757)
    at JitCompiler._compileTemplate (compiler.js:33732)
    at eval (compiler.js:33634)
    at Set.forEach (<anonymous>)
    at JitCompiler._compileComponents (compiler.js:33634)
    at eval (compiler.js:33504)
    at Object.then (compiler.js:455)
    at JitCompiler._compileModuleAndComponents (compiler.js:33503)

i got this by adding the sample code to a brand new ng new application.

DOES NOT SUPPORT angular 4 or 2.

I tried from angular 4.

Error: Metadata version mismatch for module /node_modules/ngx-monaco-editor/index.d.ts, found version 4, expected 3, resolving symbol AppModule in app/app.module.ts

you are using angular 5 , pl. change the description to support only 5 .

Diff

Will the Diff component?

NgxMonacoEditorConfig Not working in angular production build

I have the MonacoConfig in an extra file:

import { MonacoEditorModule, NgxMonacoEditorConfig } from 'ngx-monaco-editor';

const monacoConfig: NgxMonacoEditorConfig = {
  defaultOptions: {scrollBeyondLastLine: false},
  onMonacoLoad: () => {
    // Register a new language
    let monaco = (<any>window).monaco
    [...]

}
};
export default monacoConfig;

And I import it into app.module:

import monacoConfig from './editor/monaco-lang'
import { MonacoEditorModule, NgxMonacoEditorConfig } from 'ngx-monaco-editor';
...
imports: [
 MonacoEditorModule.forRoot(monacoConfig),
]

While serving and building everything acts normal, but when I build it as production the editor does not load and I am getting this error:

ERROR TypeError: Cannot read property 'defaultOptions' of null
    at e.set [as options] (main.d3395c8….bundle.js:1)
    at $r (main.d3395c8….bundle.js:1)
    at main.d3395c8….bundle.js:1
    at main.d3395c8….bundle.js:1
    at bi (main.d3395c8….bundle.js:1)
    at ro (main.d3395c8….bundle.js:1)
    at main.d3395c8….bundle.js:1
    at Object.updateDirectives (main.d3395c8….bundle.js:1)
    at Object.eo [as updateDirectives] (main.d3395c8….bundle.js:1)
    at _i (main.d3395c8….bundle.js:1)

Is my config wrong or is this a common issue?

  1. If I build it without --prod it works in the browser, but not in my electron app.
    I get this error:
ERROR Error: Uncaught (in promise): TypeError: window.require.config is not a function
TypeError: window.require.config is not a function
    at onGotAmdLoader (base-editor.js:50)
    at base-editor.js:68
    at new ZoneAwarePromise (zone-mix.js:891)
    at EditorComponent.webpackJsonp../node_modules/ngx-monaco-editor/base-editor.js.BaseEditor.ngAfterViewInit (base-editor.js:42)
    at callProviderLifecycles (core.js:12706)

Is something wrong with the way I import my config?

Access global monaco object before editor creation.

I want to use this piece of code:

monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
	noSemanticValidation: true,
	noSyntaxValidation: false
});

However, when the Angular component is initializing, the monaco object is undefined, and my component crashes. The only way I could access it is using the onInit() event, but then the editor is already initialized so the code mentioned above doesn't work anymore.

Is it possible to achieve what I want?

Editor does not show diagnostic errors in tooltips

The editor does not seem to be displaying the diagnostic errors in the tooltip when you have the validate diagnosticsOptions set to true.

You can reproduce this by setting the language on this line to 'json':
https://github.com/atularen/ngx-monaco-editor/blob/master/src/app/app.component.ts#L77

The JSON diagnostic options are already set to validate in app.module.ts.

This is what you see when you hover over an error in the editor:
image

It says undefined. Instead, it should display the actual error. I am seeing this for all languages, so the problem is not with the language itself - it is returning the correct error.

This is working fine in the monaco-editor demo:

image

Any idea where the issue might be and how to debug it?

Editor works in ng-serve/development mode but fails in production

package.json:

{
  "name": "lynx-backoffice",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
    "build": "ng build",
    "buildprod": "ng build --prod --base-href /ClientApp/dist/",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.0.0",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "angular-tree-component": "^7.0.1",
    "angular2-bootstrap-switch": "^0.2.3",
    "bootstrap": "3.3.5",
    "core-js": "^2.4.1",
    "css-loader": "^0.28.7",
    "jquery": "^1.12.4",
    "less": "^2.7.2",
    "less-loader": "^4.0.5",
    "ng-block-ui": "^1.0.0-beta.16",
    "ng-selectize": "^1.1.0",
    "ng2-bootstrap-modal": "^1.0.1",
    "ng2-date-picker": "^2.7.4",
    "ng2-dnd": "^4.2.0",
    "ng2-toastr": "^4.1.2",
    "ngx-monaco-editor": "^5.0.0",
    "ngx-pagination": "^3.1.0",
    "ngx-simple-modal": "^1.3.8",
    "rxjs": "^5.5.2",
    "selectize": "^0.12.4",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "^1.5.4",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/language-service": "^5.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.3.2",
    "typescript": "~2.4.2"
  }
}

angular.cli.json
"assets": [
"assets",
"favicon.ico",
{ "glob": "**/*",
"input": "../node_modules/ngx-monaco-editor/assets/monaco",
"output": "./assets/monaco/" } ],

template:
image

Error in production:
image

(ngModelChange) will trggered after component init

When monaco is first time loaded (onMonacoLoad is called), the (ngModelChange) is not triggerd.
When I create a the same component again in a new tab, the (ngModelChange) method is called after initialized. But the value not changed actually.

Currently i have to check if the model value changed by myself .

Uncaught ReferenceError: NgZone is not defined

ngx-monaco-editor v3.x

Uncaught ReferenceError: NgZone is not defined
at base-editor.js:102
at Object.../../../../ngx-monaco-editor/base-editor.js (base-editor.js:105)
at webpack_require (bootstrap 1eae1cc9b1c19bfb8fa7:54)
at Object.../../../../ngx-monaco-editor/diff-editor.component.js (diff-editor.component.js:1)
at webpack_require (bootstrap 1eae1cc9b1c19bfb8fa7:54)
at Object.../../../../ngx-monaco-editor/editor.module.js (editor.component.js:82)
at webpack_require (bootstrap 1eae1cc9b1c19bfb8fa7:54)
at Object.../../../../ngx-monaco-editor/index.js (editor.module.js:43)
at webpack_require (bootstrap 1eae1cc9b1c19bfb8fa7:54)
at Object.../../../../../public/app/app.module.ts (app.module.ts:31)

Unable to use build-optimizer

I'm unable to use the --build-optimizer flag with Angular-CLI when using this library.
I have tracked this issue down to the following line where we should import the Observable library with rxjs/Observable instead of the generic rxjs/Rx.

Dynamic creation?

I need to be able to change the options after it's been created. So I came up with a "solution" (if you can call it that) where I destroy and then recreate the editor with the new options. But it doesn't really work. See:

// ... earlier in the code ...
this.factory = this.factoryResolver.resolveComponentFactory ( EditorComponent )
// ... later ...
this.editor = this.editorContainer.createComponent ( this.factory )
this.editor.instance.options = options
this.editor.instance.model = {
	value : this.code
}

this.editor.instance.registerOnChange ( () => {
	this.code = this.editor.instance.model.value
	this.codeChange.emit ( this.code )
} )

But it doesn't accept my options, and every time I type something, the function errors (saying this.editor.instance.model is undefined).

Help?

Angular 6 app: 'ngx-monaco-editor' is not a known element

I am trying to use ngx-monaco-editor in an Angular 6 application.

Following the exact steps of the readme:

  1. Do npm install
  2. Add assets to angular-cli.json
  3. Add MonacoEditorModule.forRoot() to the imports of app.module.ts
  4. Try to use in HTML

It gives me this error:

1. If 'ngx-monaco-editor' is an Angular component, then verify that it is part of this module.
2. If 'ngx-monaco-editor' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
      <h1>Home</h1>

      [ERROR ->]<ngx-monaco-editor></ngx-monaco-editor>
    </div>
  </div>
")

I don't understand what I'm doing wrong; please can someone point me in the right direction?

Can't disable errors validation on css editor

I added this code in my module. But the method setDiagnosticsOptions is not called, when monaco editor is initialized.

const monacoConfig: NgxMonacoEditorConfig = { onMonacoLoad: () => { monaco.languages.css.cssDefaults.setDiagnosticsOptions({ validate: true, lint: { compatibleVendorPrefixes: 'ignore', vendorPrefix: 'ignore', duplicateProperties: 'ignore', emptyRules: 'ignore', importStatement: 'ignore', boxModel: 'ignore', universalSelector: 'ignore', zeroUnits: 'ignore', fontFaceProperties: 'ignore', hexColorLength: 'ignore', argumentsInColorFunction: 'ignore', unknownProperties: 'ignore', ieHack: 'ignore', unknownVendorSpecificProperties: 'ignore', propertyIgnoredDueToDisplay: 'ignore', important: 'ignore', float: 'ignore', idSelector: 'ignore' } }); } };

Configure Script Location

Love the component, but i think it needs to allow for a configurable location for where the loader lives. We have a virtual app running on one of our servers and since there is a / in front of assets, the baseUrl is ignored. When we try to load up our app we get a 404 as the url goes from:
https://app.com/virtualappname/assets/monaco/vs/loader.js to https://app.com/assets/monaco/vs/loader.js. This prop could default to this and live off of the options object.
https://github.com/atularen/ngx-monaco-editor/blob/master/src/platform/editor/editor.component.ts#L102

For now i plan on just extending the editor and overriding the oninit method.

Update to latest monaco

The monaco you use in your component have a defect which block me to to use. Could you upgrade monaco which use in your component? Or how can I update it by myself?

Support to pass default json schema as parameter.

In monaco editor, when we create model, it have option to pass default json schema.

var model = monaco.editor.createModel(jsonCode, 'json', 'internal://server/schema.json');
this schema will be default schema for monaco editor, it will validate our code against this schema.

Example:

  1. Use following code at playground.
  2. Click on Run button.
  3. In editor, press CTRL+ SPACE.
  4. This will auto suggest keys based on our schema.
monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
    schemas: [{
      fileMatch: ['foo.json'],
      schema: {
            type: "object",
            properties: {
                p1: {
                    enum: [ "v1", "v2"]
                }
            }
        }
    }]
});


var jsonCode = [
    '{',
    "}"
].join('\n');

var model = monaco.editor.createModel(jsonCode, 'json', 'internal://server/foo.json');

monaco.editor.create(document.getElementById("container"), {
    model: model
});

Expectation:

   <ngx-monaco-editor #editor class="size-width-100 size-height-96" 
         [options]="editorOptions" [(ngModel)]="content" (ngModelChange)="validateContent()"
         (onInit)="editorInit($event)">
       </ngx-monaco-editor>

Here it should take an optional parameter to pass json schema.

Language change not reflecting in editor

I added the editor on the HTML like this:

<ngx-monaco-editor [options]="editorOptions"></ngx-monaco-editor>

Initially, the options are set to the following object in the component:

editorOptions = {theme: 'vs-dark', language: 'javascript'};

I am trying to update the editor's language by changing the 'language' property in the options like this:
I created a button and set up a click event handler on it:

<button (click)="setHTML()>Set language to HTML</button>

setHTML() {
this.editorOptions.language = 'html';
  }

I thought this would change the language in the editor as the options should be bound two way but when I type HTML in the editor, there is no intellisense.

What am I doing wrong?
Is there another way to achieve this?

Monaco monaco.d.ts Typings

I see that under ngx-monaco-editor/src/platform/editor/ there is monaco.d.ts file. Can you export this or something so that I could use it in my TypeScript ?

Got error in Angular4

When I try to use ngx-monaco-editor in my Angular app,I got the follow error:

ERROR in Error: Metadata version mismatch for module C:/Users/kai/Desktop/0110/node_modules/ngx-mona
co-editor/index.d.ts, found version 4, expected 3, resolving symbol AppModule in C:/Users/kai/Deskto
p/0110/src/app/app.module.ts

Angular verson: 4.1.3
Angular-cli verson: 1.4.3
ngx-monaco-editor verson: 3.0.0

Anyone help me?
I just did it follow the README

jQuery language add on? (request)

First of all, I searched high and low for an editor like this one, (the ngx-monaco-editor version... not the covalent version -- there are ZERO resources for using it, and it is insanely difficult) This version was so simple to set up... it's incredible.

However, resources are still a little limited for this version as well, including: what languages are available, how to implement all the different things I have seen in the demos, etc.

But down to brass tax here, from the languages that I found, jQuery is not one of the ones included, and I was hoping that could be an add on to the languages that are currently available (also, a list would help greatly). Thanks!

window.require.config is not a function

If use this plugin in electron it showing error like this

ERROR Error: Uncaught (in promise): TypeError: window.require.config is not a function
TypeError: window.require.config is not a function

Conflict with tinymce

Tinymce's toolbar (bold, italic etc buttons) doesn't work properly, cursor moves to initial position and on clicking again leaves new line until refresh the whole app. though I am using in different components. Is there any way to destroy monaco editor when component destroy. Tinymce does same while changing component.?

ngx-monaco-editor inputs and outputs not typed

The inputs and outputs for the ngx-monaco-editor component are not typed

@Input('options')
set options(options: any) {
...
@Output() onInit = new EventEmitter<any>();

The output appears to be an monaco.editor.IStandaloneCodeEditor and the input looks to be some kind of custom interface.

Would it be possible to type these and export the types so that I can add some type safety to my app (rather than using any)

NgZone not defined

Hi there!

This is what I get when I load the page with monaco editor on it:

base-editor.js:102 Uncaught ReferenceError: NgZone is not defined

Is this something you have seen?

Access to onMonacoLoad in an editor view component

In the documentation is discriped to use the provider in the app.module

eeg:
MonacoEditorModule.forRoot(monacoConfig), // use forRoot() in main app module only.

In the monacoConfig I can access to the onMonacoLoad event.

But I need to declare this event in a "editor view component" to have access to the translations service and for tooltips the access to the current context of the component.

If there any way the define the onMonacoLoad event in the component? Or any other way to define the language definition in the running component?

thx for help.

modal is not working at all

In README find this:

@Component({
  selector: 'app-root',
  template: `<ngx-monaco-editor [options]="options" [model]="model"></ngx-monaco-editor>`,
  styles: []
})
export class AppComponent {
  options = {
    theme: 'vs-dark'
  };
  
  jsonCode = [
    '{',
    '    "p1": "v3",',
    '    "p2": false',
    '}'
  ].join('\n');

  model: NgxEditorModel = {
    value: this.jsonCode,
    language: 'json',
    uri: 'foo.json'
  };
}

I try it myself in my project and I find [model]="model" is not working at all. The jsonCode is not show in editor after page loaded. Anyone know why?

Styles are not applied

I want to change the color of the line numbers to gray. In Monaco Playground the example below is working. So what am I doing wrong ? Why is my style not applied ?

.monaco-editor.vs .line-numbers {
    color: grey;
}
<ngx-monaco-editor [ngModel]="text | async" (ngModelChange)="text.next($event)"
                   (onInit)="onEditorInit($event)" [options]="editorOptions"
                   class="monaco-editor"></ngx-monaco-editor>

found version 4, expected 3

V 3.x
@angular/core": "^4.4.3",

ERROR in Error: Metadata version mismatch for module /node_modules/ngx-monaco-editor/index.d.ts, found version 4, expected 3, resolving symbol AppModule in app/app.module.ts

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.