I am trying to implement TinyMce plugin for Angular 4, wasnt able to find a proper solution. However, I found this link providing clearly implementation of TinyMce including two-way binding – this works properly. Therefore, I would like to use this custom component in Angular form – NgForm
. If i use it in form, the component has stopped working and I am getting error of content property is null
. Can anybody tell me how to reimplement it in order to use it with form (NgForm)?
This code is taken from (little edit) link above. Without form attribute in view it works correctly.
declare let tinymce: any;
import {
AfterViewInit, Component, ElementRef, forwardRef, Input, NgZone, OnDestroy,
ViewChild
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
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) {
console.log(this.editor);
console.log(this.value);
this.editor.setContent(value);
}
}
ngAfterViewInit() {
tinymce.init({
target: this.textArea.nativeElement,
plugins: ['link', 'paste', 'table'],
skin_url: '/assets/skins/lightgray',
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);
}
}
Does not working
<form #f="ngForm" (ngSubmit)="onSubmit(f)">
<div class="form-group">
<label for="content">Page content</label>
<simple-tiny [(ngModel)]="page.content" name="content"></simple-tiny>
</div>
<button type="submit" class="btn btn-info">Add</button>
</form>
It works
<form #f="ngForm" (ngSubmit)="onSubmit(f)">
[...]
</form>
<simple-tiny [(ngModel)]="page.content" name="content"></simple-tiny>
Component holding model
export class AddEditPageComponent implements OnInit {
page: PageModel;
constructor() { }
ngOnInit() {
this.page = new PageModel();
}
onSubmit(form:NgForm){
}
}
Method from TinyMceComponent where I am receiving error message - value is null.
writeValue(value: any): void {
this.value = value;
if (this.editor) {
this.editor.setContent(value);
}
}