ng2-ckeditor 中的自定义函数

Custom function in ng2-ckeditor

我正在研究 Angular 4 项目并在其中使用 ng2-CkEditor。我已经覆盖了 CkEditor 的一些按钮的基本功能,比如保存和预览来执行我自己的功能。下面是我的代码

<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>

我正在按如下方式覆盖 OnReady() 方法中的按钮 --

public OnReady() {
    this.CkEditor.instance.addCommand("source", {
      exec: function() {
          alert("Custom handler for source button ");
      }
    });
    this.CkEditor.instance.addCommand("preview", {
      exec: function() {
           this.PreviewOfferLetter()
      }
    });
  }

PreviewOfferLetter()方法如下--

public PreviewOfferLetter() {
    const editorContentHtml = this.frmReviewOfferLetter.controls["EditorNote"].value;
    this._humanResourceService.PreviewCandidateOfferLetter(editorContentHtml).subscribe(
      data => {
        console.log(data);
      },
      error => {
        console.log(error);
      },
      () => {

      });
  }

现在,当我单击 "Preview" 按钮时,它会在控制台中抛出一个错误,显示 --

this.PreviewOfferLetter is not a function

如果我做错了什么,请提出建议。提前致谢。

您的语法正在失去 class 的上下文。考虑改用粗箭头,这样可以防止:

public OnReady() {
    this.CkEditor.instance.addCommand("source", {
      exec: () => {
          alert("Custom handler for source button ");
      }
    });
    this.CkEditor.instance.addCommand("preview", {
      exec: () => {
           this.PreviewOfferLetter()
      }
    });
  }

你也可以使用闭包,它更丑陋但也有效:

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