使用ng2-codemirror 1.1.3
lib + codemirror 5.33.0
锚点
我要做的就是将DebounceTime运算符附加到CodeMirror Editor的change
事件
HTML:
<codemirror #cm [(ngModel)]="code" [config]="config" (focus)="onFocus()" (blur)="onBlur()"></codemirror>
TS:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/debounceTime';
@ViewChild('cm') editor;
ngAfterViewInit() {
const watch = Observable.fromEvent(this.editor, 'change'); // <--- Error
watch.subscribe(v => console.log(v));
}
我得到的错误是:
错误类型错误:无效的事件目标
我也尝试将Observable.fromEvent
附加到this.editor.value
/ this.editor.input
修改 整个组件: component.HTML:
<codemirror #cm [(ngModel)]="code" [config]="config" (focus)="onFocus()" (blur)="onBlur()"></codemirror>
component.TS:
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { global } from '../shared/global.constants';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/addon/scroll/simplescrollbars';
import 'codemirror/addon/hint/javascript-hint';
import 'codemirror/addon/hint/show-hint.js';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/debounceTime';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.scss']
})
export class MainComponent implements OnInit, AfterViewInit {
@ViewChild('cm') editor;
@ViewChild('output') output;
code = global.code;
config = {
lineNumbers: true,
mode: {name: 'javascript', json: true},
tabSize: 2,
scrollbarStyle: 'simple',
extraKeys: {'Tab': 'autocomplete', 'Ctrl-Space': 'autocomplete'}
};
constructor() {
}
ngOnInit() {
}
ngAfterViewInit() {
console.log(this.editor); // <--- CodemirrorComponent {change: EventEmitter, focus: EventEmitter, blur: EventEmitter, cursorActivity: EventEmitter, instance: CodeMirror$1, …}
console.log(this.editor.nativeElement); // <--- undefined
const watch = Observable.fromEvent(this.editor.host.nativeElement, 'input');
console.log(watch);
watch.subscribe(w => console.log(w)); // <-- invalid target
}
}
答案 0 :(得分:3)
Passon元素(nativeElement
)到Observable.fromEvent
方法。
ngAfterViewInit() {
const watch = Observable.fromEvent(this.editor.nativeElement, 'change');
watch.subscribe(v => console.log(v));
}
答案 1 :(得分:3)
考虑到<codemirror>
是一个组件,@ViewChild('cm') editor
查询组件类的实例,而@ViewChild('cm') editor: ElementRef
只是欺骗键入系统但不影响editor
值。
如the reference所述,read
属性用于指定应查询哪个令牌。为了强制它ElementRef
,它应该是:
@ViewChild('cm', { read: ElementRef }) editor: ElementRef;
然后可以将事件侦听器添加到DOM元素中(正如另一个答案已经解释的那样):
const watch = Observable.fromEvent(this.editor.nativeElement, 'change');