【问题标题】:My search pipe filter don't update my template when my data changes当我的数据更改时,我的搜索管道过滤器不会更新我的模板
【发布时间】:2019-03-29 16:20:22
【问题描述】:

我正在使用这个过滤管道:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {
  transform(items: any[], field: string, value: string): any[] {
    if (!items) {
        return [];
    }
    if (!field || !value) {
        return items;
    }

    return items.filter(singleItem =>
        singleItem[field].toLowerCase().includes(value.toLowerCase())
    )}
}

输入:

<input placeholder="Nome do produto" [(ngModel)]="anunciosFiltro.name" type="text" name="filtra" id="filtra">

我有这张表,我应用了这个管道过滤器:

<div *ngFor="let tabelaAnuncioContas of sortedData?.Contas; let a = index" >
    <table>
      <tr *ngFor="let anuncio of tabelaAnuncioContas.Anuncio.products | search: 'name' : anunciosFiltro.name; let i = index">

         <td>

            <svg class="componenteTabelaResponsivo" matTooltip="Anúncio ativo" *ngIf="anuncio.status == 'enabled' && anuncio.associations[0].status == 'linked'" style="width:24px;height:24px" viewBox="0 0 24 24">
                                <path fill="rgb(161,196,66)" d="M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2Z" />
            </svg>

         </td>

      </tr>
    </table>
</div>

我的管道过滤器工作正常,但是当我过滤并进行更改我的表 (sortedData) 的数据的 http 申请时,过滤器不会更新数据:

changeDataTable(){   
 this.sortedData.Contas[this.indexContaAlterada].Anuncio.products[this.indexAnuncioAlterado].status = status;
}

我在模板中的status保持初始值。

【问题讨论】:

    标签: angular search pipe


    【解决方案1】:

    你的管道需要不纯:

    @Pipe({
      name: 'search',
      pure: false
    })
    

    https://angular.io/guide/pipes#pure-and-impure-pipes

    【讨论】:

    • 不要为我工作。我修复了使用 for() 检查数组的实际索引并更改属性: for(let i=0;i
    • 我愿意接受其他方式来做到这一点
    • 如果问题是“真正的”索引(我没有调试你的代码,因为不纯的管道是不更新视图的常见原因),那么 ngFor 中的 trackBy 选项可能会有所帮助
    • 是的,问题出在索引上。我会尝试使用 trackby
    • 我理解纯:false,当模板中的元素被移除时这个工作
    【解决方案2】:

    这与管道的处理方式有关,主要是纯管道和非纯管道的区别,如here所述。

    您可以通过以下方式将管道设置为在类装饰器上不纯:

    @Pipe({
      name: 'search',
      pure: false
    })
    

    但是你应该非常小心如何使用它。 angular 的第一个版本同时具有 filter 和 orderBy 管道,它们是有意删除的。原因描述here

    因此,我建议您尽可能避免使用管道。否则,您可能会使管道不纯(如上所示),这将导致您期望的行为。

    【讨论】:

    • 不要为我工作。我修复了使用 for() 检查数组的实际索引并更改属性: for(let i=0;i
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多