如何在 Angular2 组件中访问代码镜像文本区域值

How to Access codemirror text area value in Angular2 Component?

本文关键字:镜像 代码 文本 区域 访问 Angular2 组件      更新时间:2023-09-26

我正在尝试将codemirror与Angular 2(TypeScript)链接起来。现在,我能够使用代码区自定义指令显示代码编辑器,该指令动态加载脚本文件并格式化文本区域。

我无法获取值,用户在文本区域中键入,我已经尝试了NgModel,值等,我认为codemirror正在删除文本区域并再次重新插入,这可能会导致错误。

我尝试使用 onchange 和 keyup 事件处理程序,但是当在文本区域中输入任何内容时,它们会被重复调用。所以这是没有用的。

这是代码区组件的代码:

import {Component, AfterViewChecked,AfterViewInit} from 'angular2/core';
@Component({
    selector: 'code-area',
    template: `
    <input [(ngModel)]="ic_code">
    <textarea [(ngModel)]="ic_code" id='problem2' name='problem2' rows='10' cols='80'>
    </textarea>
    <div>
    <textarea [(ngModel)]="ic_code" id='problem1' name='problem2' rows='10' cols='80'>
    int main(){
    }
    </textarea>
    </div>
    <button (click)="submit_clicked()">Submit</button>
    <input [(ngModel)]="ic_code">
    `
})
export class CodeArea implements AfterViewInit,AfterViewChecked{
    public ic_code;
    public ic_code2;
    public ic_codediv;
    constructor(){
        this.ic_code = "";
        System.import('app/applycodemirror')
            .then(refToLoadedScript => {
                applycodestyle();
            });
    }
    ngAfterViewInit(){
        console.log("AFter view init called in CodeArea");
    }
    ngAfterViewChecked(){
    }
    onChange(){
        //This is being repeatedly called
    }
    submit_clicked() {
        //I need the code here ,when user clicks on submit
    }
    onKey(event: any) {
        console.log(event.target.value+' ');
    }
}

这是外部js文件

function applycodestyle(){
      if(document.getElementById("problem1") != null){
        console.log("Problem 1 present");
        var cEditor = CodeMirror.fromTextArea(document.getElementById("problem1"), {
          lineNumbers: true,
          matchBrackets: true,
          mode: "text/x-csrc",
        });
      }else{
        console.log("Problem 1 null");
      }
}

我使用它的方式有点不同,但也许它会帮助你。Basiaclly in ngAfterViewInit 我使用 elementRef 创建代码镜像实例:

this.cm = CodeMirror(this.elementRef.nativeElement, options);

然后在 onChange 事件中:

this.cm.on('change', (editor: CodeMirror.Editor) => {
  editor.getDoc().getValue();
});

如果您不想使用 onChange,则始终可以从代码镜像实例中获取值,例如。

cmInstance.getEditor().getDoc().getValue()

您可以使用 ng2-codemirror

安装

npm install ng2-codemirror --save

设置

systemjs.config.js

/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    var data = {
        paths: {
            // paths serve as alias
            'npm:': '/node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: '/Template/js/kpxl/app',
            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic':
                'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            //Add these code mirror packages
            'ng2-codemirror': 'npm:ng2-codemirror',
            'codemirror': 'npm:codemirror',
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            codemirror: {
                main: 'lib/codemirror.js',
                defaultExtension: 'js'
            }
        }
    };
    data.packages['ng2-codemirror'] = { main: 'lib/index.js', defaultExtension: 'js' };
    System.config(data);
})(this);

使用示例

在页面中包含 CodeMirror css 文件

<link href="/node_modules/codemirror/lib/codemirror.css" rel="stylesheet" />
<link href="/node_modules/codemirror/theme/ambiance.css" rel="stylesheet" />

在主模块中包含CodemirrorModule

import { CodemirrorModule } from 'ng2-codemirror';
@NgModule({
  // ... 
  imports:      [
    CodemirrorModule
  ],
  // ... 
})
export class AppModule { }

在您的任何Component中使用。

import { Component } from 'angular2/core';
@Component({
  selector: 'sample',
  template: `
    <codemirror [(ngModel)]="code"
      [config]="{...}"
      (focus)="onFocus()"
      (blur)="onBlur()">
    </codemirror>
  `
})
export class Sample{
  constructor(){
    this.code = `// Some code...`;
  }
}