【问题标题】:How to invoke method from filterFunction() in ng2-smart-table?如何从 ng2-smart-table 中的 filterFunction() 调用方法?
【发布时间】:2022-05-05 00:28:00
【问题描述】:

我正在尝试使用“this”关键字从 filterfunction() 调用方法。但是,我意识到“this”指的是事件处理程序而不是组件,并且我为“this”得到的值为 null,所以我得到一个运行时错误。

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-smart-table 中的 filterFunction 调用组件的方法?

【问题讨论】:

    标签: angular ng2-smart-table


    【解决方案1】:

    看起来,通过使用 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;
      }
    }
    

    我的想法在这里:Angular 4 , 'this' is undefined when using callback 'onComponentInitFunction' function of ng2-smart table

    【讨论】:

      【解决方案2】:

      问题在于,调用此函数的人将设置 this 变量,因此您对 this 在函数中的含义的想法已经改变。要将 this 修复到函数(并防止其更改),您可以使用 Bind。以下代码显示了(希望)工作示例。

      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;
        }
      }
      

      我之前的解释比严格正确更直观,如果你真的想知道它是如何工作的,请查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

      【讨论】:

      • .bind(this) 似乎没有在 Visual Studio 中编译
      【解决方案3】:

      使用下面的 filterFunction

          ...
          filterFunction: (cell?: any, search?: string): boolean => {          
                    return this.doFilter(cell, search);
          }
          ...
      

      【讨论】:

        猜你喜欢
        • 2020-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-08
        • 2020-01-03
        • 2018-12-31
        • 1970-01-01
        相关资源
        最近更新 更多