我一直在关注这个视频:https : //www.youtube.com/watch?v= 0IXelrVEoWI和相应的github来源:https : //github.com/tabvn/angular-blog
它非常适合创建新内容,但是当尝试在同一编辑器中加载和编辑现有内容时,我遇到了一些问题。
我的html dom元素看起来像这样:
<div class="row">
<div class="form-group col-lg-10">
<label for="description">description:</label>
<text-editor [value]="defaultBodyValue" [elementId]="'description'" (onEditorKeyup)="onBodyTextEditorKeyUp($event)"></text-editor>
</div>
</div>
在我的组件中,我从ngOnInit()调用此方法:
getDescription(): void {
let id;
this.route.params.forEach((params: Params) => {
id = +params['id'];
})
this.descService.getDesc(id).then(desc => this.desc = desc);
this.defaultBodyValue = "asd";
}
为了测试目的,我已经将描述硬编码为“ asd”。
我的editor.component.ts源看起来像这样:
export class EditorComponent implements OnInit, AfterViewInit, OnDestroy, OnChanges {
@Input() elementId: string;
@Input() value: any = "";
@Output() onEditorKeyup: EventEmitter<any> = new EventEmitter<any>();
baseURL: string = '/';
constructor() {
}
ngOnInit() {
}
editor;
ngAfterViewInit() {
tinymce.init({
selector: '#' + this.elementId,
plugins: ['link', 'paste', 'table', 'lists', 'hr', 'emoticons', 'advlist'],
skin_url: this.baseURL + 'assets/skins/lightgray',
setup: editor => {
this.editor = editor;
editor.on('keyup', () => {
const content = editor.getContent();
this.onEditorKeyup.emit(content);
});
},
});
}
ngOnDestroy() {
tinymce.remove(this.editor);
}
didSetValue: boolean = false;
ngOnChanges(){
console.log(this.value);
console.log("TEST: " + this.editor);
if(!isNullOrUndefined(this.editor) && this.value !== "" && !this.didSetValue){
console.log(this.value);
this.didSetValue = true;
this.editor.setContent(this.value);
}
}
}
在创建新内容时,它可以完美工作,但是当我尝试编辑内容时,它将以下内容记录到控制台:
asd
editor.component.ts:55 TEST: undefined
更新了ngAfterViewInit()函数:
ngAfterViewInit() {
tinymce.init({
selector: '#' + this.elementId,
plugins: ['link', 'paste', 'table', 'lists', 'hr', 'emoticons', 'advlist'],
skin_url: this.baseURL + 'assets/skins/lightgray',
setup: editor => {
editor = editor;
editor.on('keyup', () => {
const content = editor.getContent();
this.onEditorKeyup.emit(content);
});
},
});
}
我认为问题在于this
您尝试引用editor
变量时会用到它。在设置功能中,您可以进行以下分配:
this.editor = editor;
...我相信该this
函数内部将引用setup函数的上下文。当安装程序运行完成时,您没有editor
为EditorComponent中定义的变量分配任何内容(但在安装程序函数之外)。
然后,当您尝试editor
在ngOnChanges
方法中引用变量时,它现在引用了EditorComponent中的变量,但由于您从未对其进行初始化,因此其值为undefined
。
编辑:
如果您具有元素的ID(就像您在组件的一个变量中一样),则可以使用tinymce.get()
原始文本区域的ID并将其传递给它-应该会为您提供该ID的特定TinyMCE实例。
我相信你可以做这样的事情:
tinymce.get(this.elementId)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句