2017-10-05 60 views
2

綁定這是我tinymce.component.ts微小的MCE兩路與角2/4

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

,現在我使用它在我的HTML作爲下現在我可以通過keyupHandlerFunction的文字,但我想和2路結合ngModel

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

此代碼是TinyMCE的建議是什麼,但我想在這裏ngModel爲 2路結合我怎麼能做到這一點這裏

喜歡:

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

<p>{{ "My Model" + model}} </p> 

回答

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

Stackblitz Example

Example inside form

+0

菊st試了一下,就像一個魅力! –

+1

這工作完美無瑕,但我擔心我不知道發生了什麼事情。謹慎闡述? – balslev

+0

非常感謝! –