Auto-format XML in Monaco Editor

1.8k views Asked by At

I use the ngx-monaco-editor package in my Angular app to use Monaco Editor. I'm trying to set auto-formatting for XML content.

Component

@Component({
  selector: 'app-my-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {

  editorOptions = {
    language: 'xml',
    autoIndent: 'full',
    formatOnPaste: true,
    formatOnType: true,
    automaticLayout: true
  };
  code: string= '<parent><child></child></parent>';
...

Template

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

Actual Result

enter image description here

Expected Result

How to achieve the expected result?

1

There are 1 answers

0
Prasanth Sekar On

You can use the editor init event & trigger the format options manually

public initEditor(editor: any): void {
    if (editor) {
      setTimeout(() => {
        editor.getAction('editor.action.formatDocument').run();
      }, 100);
    }
  }
<ngx-monaco-editor class="editor" [options]="editorOptions" [(ngModel)]="code" (onInit)="initEditor($event)"></ngx-monaco-editor>