Created
April 17, 2017 21:21
-
-
Save FluffierThanThou/62dbae7426c4c5930880b6ca8eb625a9 to your computer and use it in GitHub Desktop.
angular2 (v4) ckeditor inline directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, ElementRef, Renderer, Input, Output, EventEmitter, forwardRef, AfterViewInit } from '@angular/core'; | |
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'; | |
declare let CKEDITOR: any; | |
@Directive({ | |
selector: '[ckeditable]', | |
providers: [ | |
{ | |
provide: NG_VALUE_ACCESSOR, | |
useExisting: forwardRef(() => EditableDirective), | |
multi: true | |
} | |
], | |
}) | |
export class EditableDirective implements ControlValueAccessor, AfterViewInit { | |
private element | |
private editor: any; | |
private _value: string; | |
@Input() ckoptions: any; | |
get value() { return this._value } | |
set value( value ) { | |
this._value = value; | |
this.onChange(value); | |
this.onTouched(); | |
} | |
constructor( | |
elementRef: ElementRef, | |
private renderer: Renderer | |
) { | |
this.element = elementRef.nativeElement; | |
this.renderer.setElementAttribute( this.element, 'contenteditable', 'true' ); | |
} | |
ngAfterViewInit() { | |
if (typeof CKEDITOR == 'undefined') { | |
console.warn('CKEditor not available'); | |
} else { | |
// stop auto-replacing inline components | |
CKEDITOR.disableAutoInline = true; | |
this.element | |
// CKEditor inline | |
this.editor = CKEDITOR.inline( this.element, this.ckoptions ); | |
// Set initial value | |
this.editor.setData(this.value); | |
// CKEditor change event | |
this.editor.on('change', () => { | |
this.onTouched(); | |
this.value = this.editor.getData(); | |
}); | |
} | |
} | |
/** | |
* On component destroy | |
*/ | |
ngOnDestroy() { | |
if (this.editor) { | |
setTimeout(() => { | |
this.editor.removeAllListeners(); | |
this.editor.destroy(); | |
this.editor = null; | |
}); | |
} | |
} | |
/** | |
* Implements ControlValueAccessor | |
*/ | |
writeValue(value) { | |
this._value = value; | |
if (this.editor) | |
this.editor.setData(value); | |
} | |
onChange(_) {} | |
onTouched() {} | |
registerOnChange(fn) { this.onChange = fn; } | |
registerOnTouched(fn) { this.onTouched = fn; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the code. it helped me and saved my lots of time.
:)