Search code examples
angulartypescripttabulator

Angular router.navigate not working with cell click in tabulator.info js


Im using tabulator.info js in my angular project to load table. This has Angular Framework Support as mentioned in their docs. I have a action column to place edit button in that column formatter. The problem is that routerLink is also not working and the this.router.navigate in cell click function is also not working. this.router.navigate throws the following error

cannot read property navigate of undefined

but alert() function inside the cell click is triggered.

I'm new to Angular. Please assist. I'm using this tabulator as component and using it as mentioned in their docs.

Imports

import { Component, ViewEncapsulation, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';

Constructor

constructor(private router: Router) {}

OnInit

ngOnInit() {
    this.columnNames = [
      {
        title: "Question",
        field: "description"
      },
      {
        title: "Total Answers",
        field: "",
        formatter: function (cell) {
          return cell.getRow().getData().answers.length;
        }
      },
      {
        title: "Feedback Type",
        field: "feedbackType"
      },
      {
        title: "Action",
        field: "",
        formatter: function (cell) {
          //cell - the cell component
          //formatterParams - parameters set for the column
          //onRendered - function to call when the formatter has been rendered

          return `<a [routerLink]="/feedbackquestion/${cell.getRow().getData().id}/edit" class="btn btn-sm btn-inverse text-white"><i class="fa fa-edit"></i> Edit</a>`; //return the contents of the cell;
        },
        cellClick: function (e, cell) {
          //e - the click event object
          //cell - cell component
          this.router.navigate([`/feedbackquestion/${cell.getRow().getData().id}/edit`]);
        },
      }
    ];
  }

Solution

  • It's because you're providing your cell click listener as a normal function, therefore the context inside the function changes and this is undefined.

    To keep the context of your component class, you need to provide your listener as a so-called arrow function.

    // ...
    
    cellClick: (e, cell) => {
      this.router.navigate([`/feedbackquestion/${cell.getRow().getData().id}/edit`]);
    },
    
    // ...