I am working on Angular 4 project and using ng2-CkEditor in it. I have overridden the basic functionality of some buttons of the CkEditor like Save and Preview to execute my own function. Below is my code
<ckeditor (ready)="OnReady()" [config]="editorConfig" formControlName="EditorNote" #CkEditor>
<ckbutton
[name]="'customButton'"
[command]="'customCmd'"
[label]="'Click Me'"
[toolbar]="'CustomToolBar'"
[icon]="'https://avatars1.githubusercontent.com/u/5500999?v=2&s=16'">
</ckbutton>
</ckeditor>
I am overriding the buttons in the OnReady() method as follows --
public OnReady() {
this.CkEditor.instance.addCommand("source", {
exec: function() {
alert("Custom handler for source button ");
}
});
this.CkEditor.instance.addCommand("preview", {
exec: function() {
this.PreviewOfferLetter()
}
});
}
The PreviewOfferLetter() method is as follows --
public PreviewOfferLetter() {
const editorContentHtml = this.frmReviewOfferLetter.controls["EditorNote"].value;
this._humanResourceService.PreviewCandidateOfferLetter(editorContentHtml).subscribe(
data => {
console.log(data);
},
error => {
console.log(error);
},
() => {
});
}
Now when I am clicking the "Preview" button it throws an error in console which says --
this.PreviewOfferLetter is not a function
Please suggest if I am doing something wrong. Thanks in advance.
You're losing the context of your class with your syntax. Consider switching to fat arrows, which prevent that :
public OnReady() {
this.CkEditor.instance.addCommand("source", {
exec: () => {
alert("Custom handler for source button ");
}
});
this.CkEditor.instance.addCommand("preview", {
exec: () => {
this.PreviewOfferLetter()
}
});
}
You can also use closures, which is uglier but also works :
public OnReady() {
const self = this;
this.CkEditor.instance.addCommand("source", {
exec: function() {
alert("Custom handler for source button ");
}
});
this.CkEditor.instance.addCommand("preview", {
exec: function() {
self.PreviewOfferLetter()
}
});
}