如何在quill编辑器中设置字符限制

问题描述 投票:2回答:5

我在角度2中使用Quill Editor,并希望限制用户输入最大1000个字符。

angular quill
5个回答
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提供文本更改处理程序,以防止泄漏。

Edit

使用ngx-quill模块添加解决方案。

Editor component

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

editor.template.html

<quill-editor (onContentChanged)="textChanged($event)"></quill-editor>

0
投票

同样对于ngx-quill,jgranstrom提案的一个变体专注于控制HTML长度。一个Typescript代码,一种简单的解决方法,但仍然可用。

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);
 }
}

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>

0
投票

以下是使用ngx-quill的示例。

这样做的一种方法是将maxLength设置为所需的数字并向用户显示错误。此外,可以阻止该操作,直到用户修复它。

See Image:

ngx-quill-length-validation

在这里,我添加了minLength和maxLength属性。它将在编辑器下方显示一条消息并禁用操作按钮。只有在满足验证时,该按钮才会激活。

See Code Here:


    <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>


0
投票

通过添加以下代码修复了Angular 7中的问题。

@ViewChild('editor') editor: Editor;
  setTimeout(() => {
    this.editor.writeValue(data);
    this.editor.quill.setSelection(null, data.length, null);
  }, 100);
© www.soinside.com 2019 - 2024. All rights reserved.