【问题标题】:Angular pipe length result角管长度结果
【发布时间】:2022-01-14 14:07:30
【问题描述】:

我正在使用管道,因此我可以按给定属性过滤数组。假设它是一个 id。

<div #objs *ngFor="let obj of (arrayOfObj | pipe : search)">
   ...
</div>

我还在包含数组的元素中添加了一个 ViewChildren。

@ViewChildren("objs") objs;

这是控制管道的输入:

<input type="text" [(ngModel)]="search" (ngModelChange)="inputSearch()">

这个inputSearch()函数应该在每次输入值改变时简单地控制一个带有过滤数组长度的数字变量:

inputSearch(){
    this.lengthFilteredArray = this.objs.length;
    console.log(this.objs);
}

另外,如果我记录 objs 它包含一个奇怪的结果,它有两个不同的长度(我需要第二个结果,0):log result

下面是管道的transform()

transform(array: Array<any>, search: string)
    {
      if (!array|| !search) {
        return array;
      }

      return array.filter(o =>
        o.name.toLowerCase().indexOf(search.toLowerCase()) !== -1);
    }

使用这种方法,我会得到一个“延迟”的结果。当我键入一个字符时,只有在我键入下一个字符后才能收到所需的结果。示例:我输入“x”,lengthFilteredArray 为 4,但数组被过滤为 0。如果我删除“x”,lengthFilteredArray 为 0,甚至没有过滤数组。

我不知道这是否是解决这个问题的最佳方法。

【问题讨论】:

    标签: angular pipe


    【解决方案1】:

    问题是您在“search 变量”中检查ngModelChange 的长度,此时this.objs 尚未完成处理或管道未返回过滤操作数据。

    当管道返回过滤器数据时(这里没有事件)或 ngFor 完成数据处理时(this.objs.changes 中有事件),您必须检查结果

    stackblitz example

      export class AppComponent implements AfterViewInit {
    
      @ViewChildren('objs') objs: QueryList<any>;
    
      ngAfterViewInit(): void {
        this.objs.changes.subscribe((obj) => this.log(obj));
      }
    
      log = (q) => console.log(q); // in your case check q.length here not on search change
    }
    

    【讨论】:

    • 是的,也可以,我已经包含了更长的路径,以防您需要超过长度。
    • @Kauls 如果我直接考虑使用observer.lenght 将不起作用,因为不会在正确的时间触发观察更改。所以它是偶然的,在答案中使用我的方式总是有效的。
    • 不知何故,我犯了一个错误。每次我在输入字段中键入内容时,此解决方案似乎都会增加 Length 属性。
    • 我需要更新lengthFilteredArray 每次我根据过滤数组的长度输入一些内容。我怎么能做到这一点?
    • 这正是它的作用,你能举一个stackbitz的例子来说明你是如何植入它的
    猜你喜欢
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 2021-10-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多