Search code examples
angularangular-materialangular7tabulator

Tabulator cell click: How to call a function in angular on cell click and use component elements


I am trying to use Tabulator for tables in angular 7. I am trying to call a function on cell click such that the function should open a MatDialog box and display row information. However, the problem is that when I try to access any of the Component variables (dialog: MatDialog) inside the called function, it is undefined. On debugging I found that the function is called inside the Tabulator and not in the angular component. Is there a way to call a function in the Angular and access component variables inside the function?


export class ExampleTableComponent implements OnInit {
exampleTable: Tabulator;

 constructor(private dialog: MatDialog) { }

ngOnInit() {

    this.exampleTable = new Tabulator("#ex-table-div",{
      height : 300,
      data: this.example_data,
      layout: "fitColumns",
      columns: [
        { formatter:"rownum", align:"center", width:40},
        { formatter: this.printIcon, width:40, align:"center", 
         cellClick: this.openDialog
        },
        .......
      ],
      ......
    });
}


openDialog(e, cell){

    const dialogConfig = new MatDialogConfig();

          dialogConfig.disableClose = true;
          dialogConfig.autoFocus = true;

          this.dialog.open(DetailsComponent, {      
            width: '300px',
          });

     ..........
  }
......
}

Solution

  • ES6 introduce lambda also called arrow function. The main deference is the scope of this.

    • function: scope of this = caller (Tabulator)
    • lambda: scope of this = classe where the lambda is (ExampleTableComponent)

    It can be done without this ES6 syntax using cellClick: this.openDialog.bind(this) but I personally prefer lambda.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions