Tiny Mce Two way Binding with Angular 2/4

前端 未结 1 1378
孤独总比滥情好
孤独总比滥情好 2021-01-13 19:23

This is my tinymce.component.ts

import {
  Component,
  OnDestroy,
  AfterViewInit,
  EventEmitter,
  Input,
  Output
} from \'@angular/core\';
         


        
相关标签:
1条回答
  • 2021-01-13 20:08

    You should implement ControlValueAccessor something like this:

    export const TINYMCE_VALUE_ACCESSOR: any = {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => SimpleTinyComponent),
      multi: true
    };
    
    @Component({
      selector: 'simple-tiny',
      template: `<textarea #textArea [value]="value"></textarea>`,
      providers: [TINYMCE_VALUE_ACCESSOR]
    })
    export class SimpleTinyComponent implements AfterViewInit, 
                                         OnDestroy,  ControlValueAccessor {
      @Input() elementId: String;
    
      @ViewChild('textArea') textArea: ElementRef;
    
      editor: any;
    
      value: string;
    
      onChange = (_: any) => { };
    
      constructor(private zone: NgZone) {}
    
      writeValue(value: any): void {
        this.value = value;
        if (this.editor) {
           this.editor.setContent(value || '');
        }
      }
    
      ngAfterViewInit() {
        tinymce.init({
          target: this.textArea.nativeElement,
          plugins: ['link', 'paste', 'table'],
          setup: editor => {
            this.editor = editor;
            editor.on('keyup', () => {
              const content = editor.getContent();
              this.zone.run(() => this.onChange(content))
            });
          }
        });
      }
    
      registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
      registerOnTouched(fn: () => void): void { }
    
      ngOnDestroy() {
        tinymce.remove(this.editor);
      }
    }
    

    Stackblitz Example

    Example inside form

    0 讨论(0)
提交回复
热议问题