如何在Angular2组件中访问codemirror文本区域值?

时间:2016-03-21 11:50:47

标签: javascript angularjs typescript angular codemirror

我正在尝试将codemirror与Angular 2(TypeScript)相关联。 现在,我可以使用codearea自定义指令显示CodeEditor,该指令动态加载脚本文件并格式化文本区域。

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

我曾尝试使用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");
      }
}

2 个答案:

答案 0 :(得分:3)

我使用它有点不同但也许它会帮助你。 在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()

答案 1 :(得分:0)

您可以使用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...`;
  }
}