atularen / ngx-monaco-editor

Monaco Editor component for Angular 2 and Above
https://www.npmjs.com/package/ngx-monaco-editor
MIT License
428 stars 155 forks source link

Setting focus programmatically #110

Open Myrmex opened 5 years ago

Myrmex commented 5 years ago

I'm trying to set the focus to the monaco editor on page load, and whenever its container tab (using it inside a mat-tab-group) is selected: is it possible? I've tried to add the autofocus attribute to the ngx-monaco-editor element in HTML to get focus on page load, but no luck. I then tried to get a reference to the element and call the focus method of the editor, like this:

HTML:

<ngx-monaco-editor id="query" formControlName="query" [options]="editorOptions" autofocus #queryel></ngx-monaco-editor>

TS:

@ViewChild('queryel') private _queryElementRef: ElementRef;

ngOnInit() {
  (this._queryElementRef as any)._editorContainer.nativeElement.focus();
}

Yet this does not seem to have any effect. I tried to wrap it inside a setTimeout, like this:

    setTimeout(() => {
      (this._queryElementRef as any)._editorContainer.nativeElement.focus();
    }, 500);

Still no luck. Could anyone suggest a way of programmatically setting focus to the control so that once the page loads (or its container tab gets selected) the user can just start typing?

hkeio commented 5 years ago

I got it working with a little hacky method because the component does not expose the editor property.

import { EditorComponent } from 'ngx-monaco-editor';
...
  @ViewChild('editor', { static: false }) editor: EditorComponent
  ngOnInit() {
    this.editor['_editor'].focus()
  }

Edit: even better solution: use the onInit output (https://github.com/atularen/ngx-monaco-editor#events)

onInit(editor) {
  editor.focus()
}