我在角度2中使用Quill Editor,并希望将用户限制为 输入最大1000个字符。
答案 0 :(得分:3)
据我所知,没有内置配置。但是,您可以删除超过一定长度的输入。
来自this github问题的示例代码
const limit = 1000;
quill.on('text-change', function (delta, old, source) {
if (quill.getLength() > limit) {
quill.deleteText(limit, quill.getLength());
}
});
目前尚不清楚您是否使用纯羽毛笔或类似ngx-quill之类的东西,因此我无法提供完整的示例。如果您需要有关将其集成角度的其他帮助,请提供更多详细信息。
请记住quill.off(...)
上的文字更改处理程序ngOnDestroy
以防止泄密。
使用ngx-quill模块添加解决方案。
editor.component.ts
import { Component } from '@angular/core';
const MAX_LENGTH = 10;
@Component({
selector: 'editor',
templateUrl: './editor.component.html',
})
export class EditorComponent {
/*
* Delete added characters that exceeds max length
*/
textChanged($event) {
if ($event.editor.getLength() > MAX_LENGTH) {
$event.editor.deleteText(MAX_LENGTH, $event.editor.getLength());
}
}
}
editor.template.html
<quill-editor (onContentChanged)="textChanged($event)"></quill-editor>
答案 1 :(得分:0)
同样对于ngx-quill,jgranstrom提案的一个变体专注于控制HTML长度。一个打字稿代码,一种简单的解决方法,但仍然可用。
onContentChanged(context: ChangeContext) {
console.log('Content changed: ', context);
if (context == null || context.html == null) { return; }
// A HTML - focused version of https://stackoverflow.com/questions/42803413/how-can-i-set-character-limit-in-quill-editor
// It does cause an error log in the console: 'The given range isn't in document.'
// Still it's a simple and effective solution.
if (context.html.length > RESOURCE_TEXT_MAX_LENGTH) {
let oldDelta = context['oldDelta'];
if (oldDelta == null) { return; }
context.editor.setContents(oldDelta.ops);
}
}
答案 2 :(得分:0)
内置配置支持最小长度和最大长度验证。但是它不会添加'errors.minlength'类。它只会添加'ng-invalid'类。
<quill-editor [(ngModel)]="topic.description" [bounds]="'self'" [minLength]="'5'" #topicDesc="ngModel">
<span *ngIf="!topicDesc.valid" class="requiredField">
Topic Description is required
</span>
答案 3 :(得分:0)
以下是使用ngx-quill的示例。
一种执行此操作的方法是将maxLength设置为所需的数字,并向用户显示错误。此外,可以阻止该操作,直到用户修复该问题为止。
在这里,我添加了minLength和maxLength属性。它将在编辑器下方显示一条消息,并禁用操作按钮。只有在通过验证后,该按钮才会处于活动状态。
<quill-editor [style]="{height: '200px'}" name="notes"
[(ngModel)]="note" [minLength]="10" [maxLength]="400"
#noteInput="ngModel"></quill-editor>
<span class="hints" *ngIf="!noteInput.valid">
Min 10 characters and note more than 400</span>
<button fxFlexAlign="end" mat-raised-button color="primary"
class="btn--rounded" (click)="addNote()"
[disabled]="!ticketNoteInput.valid">Add</button>
答案 4 :(得分:0)
通过添加以下代码在Angular 7中进行了修复。
@ViewChild('editor') editor: Editor;
setTimeout(() => {
this.editor.writeValue(data);
this.editor.quill.setSelection(null, data.length, null);
}, 100);