9

I'm using ngx-monaco-editor to implement a code editor in a modal. Because I need to support multiple tabs, I need to prepare a map for models to remember the models with Uris. The modal can also be reopened after closing it.

Question: Once I reopen the modal and choose a file previously opened, it will throw error:

Cannot add model because it already exists

I'm not sure why ngx-monaco-editor does not destroy the models after the component is destroyed.

Is there a way that I can manually clear those models before closing the modal.

huan feng
  • 7,307
  • 2
  • 32
  • 56

2 Answers2

18

Below approach is the way i find so far:

monaco.editor.getModels().forEach(model => model.dispose());

Getting all the models and calling its dispose method in component destroy method.

huan feng
  • 7,307
  • 2
  • 32
  • 56
2

If you have a hash that references the models, you can just call dispose on the model instance via the hash:

hashOfModels[uri].dispose();

Because the models only represent the state of the text file, you also have to stash the editor state (see editor.saveViewState and editor.restoreViewState), else the editor will basically scroll to the beginning of the file (and place the cursor there) every time you switch tabs.

You can just stash the model and view together. Basically, create a hash named something like editorState, and for each open file, use the file's path as the key and a {model, view} hash to store the state of the editor.

When you first load a model (for a newly opened file) into the editor (with editor.setModel), the editor will be in its initial state, so you can call editor.saveViewState immediately afterwards to get a view instance you can use as a starting point.

Every time you switch tabs, stash the current view and model, before loading the ones you're switching to.

Whenever you create a new model, use a try-catch, and if the model already exists, just switch to the corresponding tab (so opening an open file just focusses it) instead of creating a new one (making sure anything you already initialized in the openFile function will be GCed).