Reputation: 991
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?
Upvotes: 1
Views: 2969
Reputation: 19
Use filterFunction like below
...
filterFunction: (cell?: any, search?: string): boolean => {
return this.doFilter(cell, search);
}
...
Upvotes: 0
Reputation: 991
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
Upvotes: 2
Reputation: 486
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
Upvotes: 1