Angular 如何从ng2智能表中的filterFunction()调用方法?
我正在尝试使用'this'关键字从filterfunction()调用方法。但是,我意识到“this”指的是事件处理程序而不是组件,并且我为“this”获取的值为null,因此我得到一个运行时错误Angular 如何从ng2智能表中的filterFunction()调用方法?,angular,ng2-smart-table,Angular,Ng2 Smart Table,我正在尝试使用'this'关键字从filterfunction()调用方法。但是,我意识到“this”指的是事件处理程序而不是组件,并且我为“this”获取的值为null,因此我得到一个运行时错误 export class SmartTableComponent { settings = { ... columns: { ... firstName: { title: 'First Name', type: 'stri
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;
}
}
在Java中,我们可以通过使用SmartTableComponent.this.doFilter(…)获得对“this”的引用,但这在TypeScript中似乎不起作用
如何从ng2智能表中的filterFunction调用组件的方法?问题是,无论是谁调用此函数,都会设置this变量,因此您对函数中这意味着什么的想法已经改变。要将此问题修复到函数(并防止其更改),可以使用。下面的代码显示了(希望如此)工作示例
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;
}
}
我前面的解释更直观,而不是严格正确。如果您真的想知道它是如何工作的,请查看似乎通过使用lambda表达式而不是匿名函数,“this”的值是从包装器类维护的。因此,这就是解决方案:
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;
}
}
我的想法是:.bind(这个)在VisualStudio中似乎不是编译器