首页 > 解决方案 > 从 jquery summernote 调用父组件函数

问题描述

我正在尝试调用我添加到 ngx-summernote 工具栏的自定义按钮组件之外的函数。我当前的代码如下。这无法编译,但我尝试过的所有其他编译方法都会给我一个错误,即它找不到函数。角度 8。

test() {
    console.log('oh hai');
  }


  customButton() {
    const ui = $.summernote.ui;
    const button = ui.button({
        contents: '<i class="note-icon-magic"></i> hello',
        tooltip: 'custom button',
        container: '.note-editor',
        className: 'note-btn',
        click: function() => {
          this.test()
        }
      });
    return button.render();
  }


  //summernote config
  config: any = {
    placeholder: 'Enter a description. You can #define up to 5 #hashtags.',
    height: "200px",
    uploadImagePath: "/api/upload",
    disableDragAndDrop: true,
    tabDisable: true,
    toolbar: [
      [
        "font",
        [
          "bold",
          "italic",
          "underline",
          "strikethrough",
          "superscript",
          "subscript",
          "color",
          "testBtn",
        ],
      ],
    ],
    buttons: {
      'testBtn' : this.customButton
    }
  };

标签: angularsummernote

解决方案


在导入语句下方的顶部声明一个变量 -

let thisContext;

在 ngOnInit 中用这个对象初始化它 -

ngOnInit() {
    thisContext = this;
}

将测试方法保留在组件类中 -

使用该变量调用 test() 函数 -

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser';
import { codeBlockButton } from 'ngx-summernote';

declare var $;
let thisContext;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
 
  constructor(private sanitizer: DomSanitizer) {}

  ngOnInit() {
    thisContext = this;
  }

  
  test(){
    console.log("hi");
  }
}

function customButton(context) {
  const ui = $.summernote.ui;
  const button = ui.button({
    contents: '<i class="note-icon-magic"></i> Hello',
    tooltip: 'Custom button',
    container: '.note-editor',
    className: 'note-btn',
    click: function() {
      context.invoke('editor.insertText', 'Hello from test btn!!!');
      thisContext.test();
    }
  });
  return button.render();
}

推荐阅读