通过Froala自定义按钮调用自定义方法

时间:2019-02-27 14:10:40

标签: angular froala

我正在开发Angular 7应用,并且在此应用中,我使用了名为Froala的WYSIWYG编辑器库。

我已经向工具栏添加了一个自定义按钮,现在我想在用户单击该按钮的同一类中调用一个方法(以打开自定义模式)。我使用下面的代码,但出现错误,提示它找不到openPictureModal方法。

$.FroalaEditor.DefineIcon('imagePicker', {NAME: 'info'});
    $.FroalaEditor.RegisterCommand('imagePicker', {
      title: 'Image picker',
      focus: false,
      undo: false,
      refreshAfterCallback: false,
      callback: function (data) {
        this.openPictureModal();
      }
    });

我收到此错误:

Uncaught TypeError: this.openPictureModal is not a function

这是我的模态方法:

openPictureModal() {
    const modalRef = this.modalService.open(PictureManageComponent, { size: 'lg' });
          modalRef.componentInstance.formFinished.subscribe(($event) => {
            modalRef.close();
          });
  }

如何通过自定义按钮在同一类中调用自定义方法?

1 个答案:

答案 0 :(得分:1)

您的代码中有两个问题。第一个非常常见,是this在回调内部丢失。将回调定义为箭头函数应解决该问题。有关更多详细信息,请参见this question

第二个问题更加微妙。作为jQuery事件处理程序的回调可能在Angular区域之外调用。因此,它不会触发更改检测。您可以将回调代码包装在NgZone.run()中以解决该问题。

结果代码如下:

import { NgZone } from '@angular/core';

constructor(private ngZone: NgZone) { }

...

initializeFroala() {
  $.FroalaEditor.DefineIcon('imagePicker', {NAME: 'info'});
  $.FroalaEditor.RegisterCommand('imagePicker', {
    title: 'Image picker',
    focus: false,
    undo: false,
    refreshAfterCallback: false,
    callback: (data) => {            // Define the callback as arrow function
      this.ngZone.run(() => {        // Run the callback code in Angular zone
        this.openPictureModal();
      });
    }
  });
}