javascript 如何从'ngx-quill'编辑器中获取值,同时将其与FormBuilder一起使用?

4nkexdtk  于 2023-04-19  发布在  Java
关注(0)|答案(1)|浏览(131)

当我尝试使用ngx-quill包为我的项目创建编辑器时,我没有从'ngx-quill'编辑器中获得值。当我提交表单(使用FormBuilder)时。我使用Angular 15和ngx-quill v21.0.0。
即使我在编辑器中键入一些标题或粗体文本,但它显示controls.content.errors.required为true,controls. content.touched为false。
我无法发现这个问题.非常感谢您的建议和帮助
editor.component.ts

quillConfig = {
    //toolbar: '.toolbar',
    toolbar: {
      container: [
        ['bold', 'italic', 'underline', 'strike'], // toggled buttons
        ['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] }],

        //[{ 'font': [] }],
        //[{ 'align': [] }],

        ['clean'], // remove formatting button

        ['link'],
        //['link', 'image', 'video']
      ],
    },

    mention: {
      allowedChars: /^[A-Za-z\sÅÄÖåäö]*$/,
      mentionDenotationChars: ['@', '#'],
      source: (
        searchTerm: string,
        renderList: (arg0: any[], arg1: any) => void,
        mentionChar: string
      ) => {
        let values;

        if (mentionChar === '@') {
          values = this.atValues;
        } else {
          values = this.hashValues;
        }

        if (searchTerm.length === 0) {
          renderList(values, searchTerm);
        } else {
          const matches = [];
          for (var i = 0; i < values.length; i++)
            if (
              ~values[i].value.toLowerCase().indexOf(searchTerm.toLowerCase())
            )
              matches.push(values[i]);
          renderList(matches, searchTerm);
        }
      },
    },
    'emoji-toolbar': true,
    'emoji-textarea': false,
    'emoji-shortname': true,
    keyboard: {
      bindings: {
        // shiftEnter: {
        //   key: 13,
        //   shiftKey: true,
        //   handler: (range, context) => {
        //     // Handle shift+enter
        //     console.log("shift+enter")
        //   }
        // },
        enter: {
          key: 13,
          handler: (range: any, context: any) => {
            console.log('enter');
            return true;
          },
        },
      },
    },
  };

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.blogForm = this.fb.group({
      title: ['', Validators.required],
      content: [null, Validators.required],
      // content: new FormControl("")
    });
  }

  onSubmit() {
    console.log(this.blogForm.value);
    console.log(this.blogForm);
  }```

editor.component.html

    <div class="tt-form-container">
  <form class="tt-blogForm" [formGroup]="blogForm" (ngSubmit)="onSubmit()">
    <h2>Write a Blog</h2>
    <div>
      <label for="title"> Title:</label>
      <input type="text" id="title" formControlName="title" />
    </div>
    <div>
      <label for="content">Content:</label>
      <quill-editor
        class="tt-blog-editor"
        theme="snow"
        formControlName="content"
        [modules]="quillConfig"
        (onBlur)="onBlur()"
        (onSelectionChanged)="onSelectionChanged()"
      >
      </quill-editor>
    </div>
    <div>
      <button class="tt-blog-button" type="submit">Submit</button>
    </div>
  </form>
</div>
sbtkgmzw

sbtkgmzw1#

如果你想使用quill编辑器作为一个Form元素,最好为quill编辑器创建一个自定义的 Package 器元素,它实现了ControlValueAccessor。ControlValueAccessor是一个与角形表单一起工作的接口。
这里有一个例子,它可能类似于这样的工作:

import { Component, forwardRef, OnDestroy, OnInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import Quill from 'quill';

@Component({
  selector: 'app-quill-editor-wrapper',
  template: `<div id="quill-editor"></div>`,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => QuillEditorWrapperComponent),
      multi: true
    }
  ]
})
export class QuillEditorWrapperComponent implements OnInit, OnDestroy, ControlValueAccessor {
  private quillEditor: Quill;
  private onChangeCallback: (value: string) => void;
  private onTouchedCallback: () => void;

  ngOnInit(): void {
    this.quillEditor = new Quill('#quill-editor', {
      theme: 'snow',
      modules: {
        toolbar: [
          [{ header: [1, 2, false] }],
          ['bold', 'italic', 'underline'],
          ['image', 'code-block']
        ]
      }
    });

    this.quillEditor.on('text-change', () => {
      this.onChangeCallback(this.quillEditor.root.innerHTML);
      this.onTouchedCallback();
    });
  }

  ngOnDestroy(): void {
    this.quillEditor.off('text-change');
  }

  writeValue(value: string): void {
    this.quillEditor.root.innerHTML = value || '';
  }

  registerOnChange(callback: (value: string) => void): void {
    this.onChangeCallback = callback;
  }

  registerOnTouched(callback: () => void): void {
    this.onTouchedCallback = callback;
  }

  setDisabledState(isDisabled: boolean): void {
    this.quillEditor.enable(!isDisabled);
  }
}

然后你可以使用它与正常的Angular Forms:

<app-quill-editor-wrapper [(ngModel)]="editorValue"></app-quill-editor-wrapper>

或使用React形式:

<app-quill-editor-wrapper formControlName="quilleditor"></app-quill-editor-wrapper>

如果您对ControlValueAccessor感兴趣:

  1. https://angular.io/api/forms/ControlValueAccessor
  2. https://www.youtube.com/watch?v=OrmIfW8Ak3w&t=831s

相关问题