'How to invoke method from filterFunction() in ng2-smart-table?
I am trying to invoke a method from a filterfunction() by using 'this' keyword. However, I realize that 'this' refers to the event handler instead the component, and the value I get for 'this' is null so I get a runtime error.
export class SmartTableComponent {
settings = {
...
columns: {
...
firstName: {
title: 'First Name',
type: 'string',
filterFunction(cell?: any, search?: string): boolean {
return this.doFilter(cell, search);
}
},
...
},
...
};
doFilter(cell?: any, search?: string): boolean{
return true;
}
}
In Java, we would get a reference to 'this' by using SmartTableComponent.this.doFilter(...) but this does not seems to work in TypeScript.
How can I invoke a component's method from a filterFunction in ng2-smart-table?
Solution 1:[1]
It seems that, by using a lambda expression instead of an anonymous function, the value of 'this' is maintained from the wrapper class. So, this is the solution:
export class SmartTableComponent {
settings = {
...
columns: {
...
firstName: {
title: 'First Name',
type: 'string',
filterFunction:(cell?: any, search?: string) => {
return this.filterByText(cell.doc[0]['value'], search);
},
},
...
},
...
};
doFilter(cell?: any, search?: string): boolean{
return true;
}
}
I got the idea here: Angular 4 , 'this' is undefined when using callback 'onComponentInitFunction' function of ng2-smart table
Solution 2:[2]
The problem is that whoever invokes this function will set the this variable, and so your idea of what this means in the function has changed. To fix the this to the function (and prevent it from changing), you can use Bind. The following code shows the (hopefully) working example.
export class SmartTableComponent {
settings = {
...
columns: {
...
firstName: {
title: 'First Name',
type: 'string',
filterFunction(cell?: any, search?: string): boolean {
return this.doFilter(cell, search);
}.bind(this)
},
...
},
...
};
doFilter(cell?: any, search?: string): boolean{
return true;
}
}
My previous explanation is more intuitive than strictly correct, if you really want to know how it works, check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Solution 3:[3]
Use filterFunction like below
...
filterFunction: (cell?: any, search?: string): boolean => {
return this.doFilter(cell, search);
}
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | TWT |
Solution 3 | Mob Apps Trends |