我正在尝试在我的 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
最佳答案
您可以检查 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 日
为此可以采取的另一种方法是:
- 如果您的元素是 ViewChild ,那么使用上面的 Lifecycle 应该会有所帮助
- 如果您希望当前元素成为编辑器,尝试注入(inject) ElementRef 也可以
关于node.js - 如何在 Angular 2 组件中初始化 Quill 编辑器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45152172/