【问题标题】:Angular Material Table filterPredicate to filter objectsAngular Material Table filterPredicate 过滤对象
【发布时间】:2020-06-15 16:59:37
【问题描述】:

我有一个带有文本输入的垫表来过滤它的结果。

数据源是:

[
    {
        "articolo": {
            "code": "22.398.14",
            "url": "/url1"
        },
        "color": "white",
        "weight": "10"
    },
    {
        "articolo": {
            "code": "22.398.15",
            "url": "/url2"
        },
        "color": "red",
        "weight": "20"
    }
]

我在 html 中添加了这个:

    <mat-form-field>
    <mat-label>Filtra</mat-label>
    <input matInput (focus)="setupFilter('articolo')" (keyup)="applyFilter($event)" placeholder="Filter">
    </mat-form-field>

在ts中:

setupFilter(column: string) {
    this.data.filterPredicate = (data, filter) => {
      data[column].code.indexOf(filter) != -1;
    }
  }

applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.data.filter = filterValue.trim().toLowerCase();
  }

但是什么都没发生

如果我在 filterPredicate 中添加一个 console.log 它不会触发:

this.data.filterPredicate = (data, filter) => {
      console.log(data);
...

怎么了?

谢谢

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    如果您需要为您的“代码”属性创建自己的过滤行为,请在构造函数或 ngOnInit 钩子中创建它,就像这样:

    ngOnInit() {
        this.dataSource = new MatTableDataSource(this.data);
        this.dataSource.filterPredicate = (data, filter) => {
          return data.articolo.code.indexOf(filter) != -1;
        }
      }
    

    注意filterPredicate中的return语句。你没用过! 此外,您不需要这个 (focus)="setupFilter('articolo')" 。 您所要做的只是调用 applyFilter,就像这样:

    applyFilter(event: Event) {
        const filterValue = (event.target as HTMLInputElement).value;
        this.dataSource.filter = filterValue.trim().toLowerCase();
        console.log(this.dataSource.filteredData);
      }
    

    然后您可以在更改输入值期间在控制台中查看过滤后的数据。 希望,我帮助了你。我不明白为什么你的数据是嵌套的。好主意是首先转换这些数据,然后应用过滤器。可能在你的情况下它很好。

    【讨论】:

      【解决方案2】:

      您正在分配一个函数,但没有调用它。

      this.data.filterPredicate = (data, filter) => { data[column].code.indexOf(filter) != -1; }

      Try

      到控制台记录 this.data.filterPredicate(data, filter)。这不会返回任何东西,arrgggh 你有一个没有返回任何东西的函数。

      Catch (e) =&gt;

      do one thing at a time: so, a function. Console log direct.
      

      【讨论】:

      • chouette go go :)
      猜你喜欢
      • 2019-10-10
      • 2018-08-01
      • 1970-01-01
      • 2020-01-02
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      相关资源
      最近更新 更多