How to formate javascript code in ngx-monaco-editor-v2 in angular 17 by calling a function?

29 views Asked by At

Hi my requirement is to make a function that format the JavaScript code, currently using "ngx-monaco-editor-v2" because its support angular 17, issue here is there is not inbuild method for format the code till today, as for monaco-editor its there but not in "ngx-monaco-editor-v2",i checked all the sources available can't find.

Searched all the sources available in internet can't get enough information possibly very new released.

1

There are 1 answers

0
Salman Khan On

Hi I found the solution to format the code below are my steps, please do follow,

1- There is no inbuild method in "ngx-monaco-editor-v2", so need to do from outside the editor.

2- I found "js-beautify" npm which worked for me also try "npm i --save-dev @types/js-beautify" simply "npm i js-beautify" will throw error.

3- Here is my function to format the code:-

//ts

this.formData.code="function test(){
                                    return('formatted successfully')
}"  


  formateCode() {
    const options:JSBeautifyOptions = { // optional
      indent_size: 2,
      indent_with_tabs: false,
      end_with_newline: true,
      space_in_paren: false,
      preserve_newlines: true,
      wrap_line_length: 80,
      brace_style: 'collapse',
    };
       let code = js_beautify(this.formData.code, options)
      this.formData.code = code
  }

// html

 <ngx-monaco-editor #monacoEdiror   (ngModelChange)="onCodeChanged($event)" [options]="editorOptions" [(ngModel)]="this.formData.code"></ngx-monaco-editor>

Hope you have got the answer.