Как добавить пользовательскую панель инструментов Quill в приложение Angular
Мое веб-приложение основано на Angular, и я пытаюсь интегрировать в него Quill с помощью библиотеки ngx-quill. Я создал свой пользовательский блот для встраивания, содержащий только неизменяемый текстовый блок (извлеченный из базы данных), и теперь я пытаюсь создать пользовательскую панель инструментов, позволяющую пользователям вставлять экземпляры этого блота в текст.
У меня вопрос: как можно создать собственный выпадающий список на панели инструментов Quill, где я могу предоставить свой собственный контент, который будет показан пользователю и вставлен в текст?
Я пытаюсь сделать это так:
<quill-editor>
<div quill-editor-toolbar>
<select class="ql-attribute">
<option *ngFor="let attribute of documentAttributes()"
[title]="document.data[attribute.id]"
(click)="onAddAttribute(attribute.id)">
{{attribute.name}}
</option>
</select>
</div>
</quill-editor>
... но в раскрывающемся меню значения не отображаются.
Похоже, что эта проблема уже решена для React и простого JS. Но похоже, что в Angular будет немного сложнее, особенно когда Quill интегрируется с использованием QuillEditorComponent, предоставляемого библиотекой ngx-quill.
1 ответ
Мне удалось сделать это через некоторое время, благодаря этой скрипке и небольшой тренировке. Смотрите здесь.
component.html:
<quill-editor [(ngModel)]="editorContent"
[options]="editorOptions"
(ready)="onEditorCreated($event)"
(change)="onContentChanged($event)"></quill-editor>
component.ts:
public editor;
public editorContent = '<h3>Type Something...</h3>';
public editorOptions = {
theme: 'snow',
modules: {
toolbar: {
container:
[
[{ 'placeholder': ['[GuestName]', '[HotelName]'] }], // my custom dropdown
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'font': [] }],
[{ 'align': [] }],
['clean'] // remove formatting button
],
handlers: {
"placeholder": function (value) {
if (value) {
const cursorPosition = this.quill.getSelection().index;
this.quill.insertText(cursorPosition, value);
this.quill.setSelection(cursorPosition + value.length);
}
}
}
}
}
};
constructor(private elem: ElementRef) {
}
onEditorCreated(quill) {
this.editor = quill;
console.log('quill is ready! this is current quill instance object', quill);
}
onContentChanged({ quill, html, text }) {
console.log('quill content is changed!', quill, html, text);
}
ngAfterViewInit() {
// Update your dropdown with labels
let placeholderPickerItems = this.elem.nativeElement.querySelectorAll('.ql-placeholder .ql-picker-item');
placeholderPickerItems.forEach(item => item.textContent = item.dataset.value);
this.elem.nativeElement.querySelector('.ql-placeholder .ql-picker-label').innerHTML
= 'Insert Data Field ' + this.elem.nativeElement.querySelector('.ql-placeholder .ql-picker-label').innerHTML;
}
Выход:
Надеюсь это поможет!
Для более поздних проектов angular 8 параметры конфигурации находятся здесь: https://github.com/KillerCodeMonkey/ngx-quill
И это можно сделать в html через
<quill-editor [modules]="editorOptions" ></quill-editor>
и класс js
export class Component {
editorOptions= {
toolbar: [[{ 'list': 'bullet' }]]
};
}