【问题标题】:How Can I insert string on the cursor position on the onClick event using ngx-codemirro text editor如何使用 ngx-codemirro 文本编辑器在 onClick 事件的光标位置插入字符串
【发布时间】:2022-11-07 18:52:44
【问题描述】:

有没有办法在 ngx-codemirro 的当前光标位置插入一个字符串?

我是 ngx-codemirror 的新手,我已经在我的 Angular 项目中为 HTML 代码编辑器集成了 ngx-codemirror,它工作正常,我还想在单击按钮时在光标位置的编辑器面板上插入一个字符串。我正在尝试一些事情,但它不起作用。请任何有 ngx-codemirror 经验的人帮助我。

ts:

  export class CodeMirroComponent implements OnInit {
         constructor() { }
         content = '<p align="center">Hello</p>';
        
          options = {
            lineNumbers: true,
            mode: 'markdown'
          };
        
          ngOnInit(): void {
          }
        
         insertString(content: any, str: any) {
            var doc = content.getDoc();
            var cursor = doc.getCursor();
            var pos = {
              line: cursor.line,
              ch: cursor.ch
            }
        
            doc.replaceRange(str, pos);
          }
        
        }

HTML:

 <div>
     <ngx-codemirror
       #codeMirror
       [options]="options"
       [(ngModel)]="content"
       [autoFocus]="true"
      >
     </ngx-codemirror>
    <button class="btn btn-sm btn-info"
           (click)="insertString(content, 'this is new line')">
              Name
    </button>
 </div>

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    根据文档。

    https://sibiraj-s.github.io/ngx-editor/en/commands/

    或使用交易

    对于 text 或 text-html

    this.editor.commands.insertText(text).exec();
    

    对于其他节点,例如提及

    const node = this.editor.view.state.schema.nodes.mention.create({
                id: profile.id,
                name: displayName(profile),
            });
            const state = this.editor.view.state;
            const tr = state.tr.replaceWith(state.selection.from, state.selection.to, node);
            this.editor.view.dispatch(tr);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-14
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 2016-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多