pivottable.js- Unable to access class variables inside clickCallback

412 Views Asked by At

I am trying to access a class variable inside callback function in pivot table, I am using angular 5 and for pivot table: nicolaskruchten/pivottable

My code:

declare var jQuery: any;

@Component({
  selector: 'app-dialog-commitment-pivot',
  templateUrl: '<div id="pivot"></div>',
  styleUrls: ['./dialog-commitment-pivot.component.scss']
})
export class DialogCommitmentPivotComponent implements OnInit {

  private el: ElementRef;

  constructor(
    private commitmentService: CommitmentService,
    public dialogRef: MatDialogRef<DialogCommitmentPivotComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    @Inject(ElementRef) el: ElementRef
  ) {
    this.el = el;
   }


  ngOnInit() {

        if (!this.el ||
          !this.el.nativeElement ||
          !this.el.nativeElement.children) {
          console.log('cant build without element');
          return;
        }

        var container = this.el.nativeElement;
        var inst = jQuery(container);
        var targetElement = inst.find('#pivot');

        if (!targetElement) {
          console.log('cant find the pivot element');
          return;
        }

        while (targetElement.firstChild) {
          targetElement.removeChild(targetElement.firstChild);
        }

        //render here
        targetElement.pivot(this.data.pivotData,
          {
            rows: ["status"],
            cols: ["name"],
            rendererOptions: {
              table: {
                clickCallback: function(e, value, filters, pivotData) {
                  console.log(e);
                  console.log(value);
                  console.log(filters.name);
                  console.log(pivotData);


                  this.commitmentService.getPivotDataDetails(filters.name, filters.status)
                    .subscribe(
                      res => {
                        console.log(res);
                      })
                }
              }
            }
          });
  }

I get error:

TypeError: Cannot read property 'getPivotDataDetails' of undefined

I am unable to access any class variables from inside clickCallback I am not sure what is wrong.

1

There are 1 best solutions below

0
On BEST ANSWER

I found the issue. It was nothing to do with pivottable, actually it was scope problem. The commitmentService was not visible inside pivottable callback. So I fixed it by doing the following:

  1. move getPivotDataDetails as a method of DialogCommitmentPivotComponent
  2. now bind getPivotDataDetails like this: clickCallback: this.getPivotDataDetails.bind(this)