我正在尝试在Angular 2项目中实现自己的Quill编辑器组件。我使用npm将quill安装到我的项目中。我正在尝试使用我的组件创建一个单词计数器应用程序。我正在尝试实现以下代码:https://quilljs.com/blog/building-a-custom-module/
HTML代码:
<div id="editor"></div>
<div id="counter">0</div>
CSS:
body {
padding: 25px;
}
#editor {
border: 1px solid #ccc;
}
#counter {
border: 1px solid #ccc;
border-width: 0px 1px 1px 1px;
color: #aaa;
padding: 5px 15px;
text-align: right;
}
这是我的组件代码:
import { OnInit, Component, ViewChild, ElementRef } from '@angular/core';
import * as Quill from 'quill';
@Component({
selector: 'app-quill-editor',
templateUrl: './quill-editor.component.html',
styleUrls: ['./quill-editor.component.css']
})
export class QuillEditorComponent{
// Implement and register module
constructor()
{
Quill.register('modules/counter', function(quill, options) {
var container = document.querySelector('#counter');
quill.on('text-change', function() {
var text = quill.getText();
// There are a couple issues with counting words
// this way but we'll fix these later
container.innerHTML = text.split(/\s+/).length;
});
});
console.log(document.querySelector('#editor'))
// We can now initialize Quill with something like this:
var quill = new Quill('#editor', {
modules: {
counter: true
}
});
}
}
当我提交申请时,我会收到:
quill Invalid Quill container #editor
答案 0 :(得分:2)
您可以检查Angular生命周期并在那里调用与Quill相关的内容,将它们放在constructor()中可能会导致错误,因为HTML元素尚未呈现。
您可以尝试将它们放入ngOnInit()或ngAfterViewInit()
export class QuillComponent implements OnInit {
constructor() {
}
ngOnInit() { // Quill initialization and querying for elements here }
}
参考:https://angular.io/guide/lifecycle-hooks
2019年3月4日
可以采取的另一种方法是: