微小的Mce双向绑定与Angular 2/4

atu*_*hra 4 tinymce tinymce-4 tinymce-3 angular

这是我的 tinymce.component.ts

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

@Component({
  selector: 'simple-tiny',
  template: `<textarea id="{{elementId}}"></textarea>`
})
export class SimpleTinyComponent implements AfterViewInit, OnDestroy {
  @Input() elementId: String;
  @Output() onEditorKeyup = new EventEmitter<any>();

  editor;

  ngAfterViewInit() {
    tinymce.init({
      selector: '#' + this.elementId,
      plugins: ['link', 'paste', 'table'],
      skin_url: 'assets/skins/lightgray',
      setup: editor => {
        this.editor = editor;
        editor.on('keyup', () => {
          const content = editor.getContent();
          this.onEditorKeyup.emit(content);
        });
      },
    });
  }

  ngOnDestroy() {
    tinymce.remove(this.editor);
  }
}
Run Code Online (Sandbox Code Playgroud)

现在我正在使用它我的html现在我可以得到文本通过keyupHandlerFunction但我想要2路绑定ngModel

<simple-tiny
      [elementId]="'my-editor-id'"
      (onEditorKeyup)="keyupHandlerFunction($event)"
     >
</simple-tiny>
Run Code Online (Sandbox Code Playgroud)

这段代码是tinyMCE建议的,但我想ngModel在这里进行双向绑定,我怎么能在这里做

喜欢:

<simple-tiny
      [elementId]="'my-editor-id'"
      (onEditorKeyup)="keyupHandlerFunction($event)"
      [(ngModel)]="value">
</simple-tiny>

<p>{{ "My Model" + model}} </p>
Run Code Online (Sandbox Code Playgroud)

yur*_*zui 6

您应该实现ControlValueAccessor,如下所示:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

Stackblitz示例

内部表格示例