Search code examples
angularsummernote

calling parent component function from jquery summernote


I'm trying to call a function that is outside of a custom button component I'm adding to ngx-summernote toolbar. My current code is below. This fails to compile, but all of the other methods I've tried where it compiles gives me the error that it can't find the function. Angular 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
    }
  };

Solution

  • declare a variable at top below imports statements -

    let thisContext;
    

    initialize it with this object inside ngOnInit -

    ngOnInit() {
        thisContext = this;
    }
    

    keep test method inside component class -

    use that variable to call test() function -

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