ng2-ckeditor中的自定义功能

时间:2018-08-08 13:24:57

标签: angular typescript 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);
      },
      () => {

      });
  }

现在,当我单击“预览”按钮时,它将在控制台中引发错误,提示-

this.PreviewOfferLetter is not a function

请建议我是否做错了什么。预先感谢。

1 个答案:

答案 0 :(得分:1)

您正在使用语法丢失类的上下文。考虑切换到粗箭头,以防止出现这种情况:

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