【问题标题】:filterOptions in Autocomplete does not work自动完成中的 filterOptions 不起作用
【发布时间】:2019-03-17 12:00:58
【问题描述】:

我有这个demo

当我单击 + 时,我可以过滤状态并正确显示状态名称。 当我再次单击 + 添加 State 时,过滤器不起作用。

我有这个过滤器代码:

this.filteredStates = this.myform.controls['products_id'].valueChanges
  .pipe(
    startWith(''),
    map(state =>  this._filterStates(state))
  );

有什么想法吗?

【问题讨论】:

  • 你能解释一下吗
  • 我的自动完成过滤器有问题。首先,我点击Add Item 并搜索o state。搜索效果很好。第二个我想添加更多项目,点击Add Item搜索但搜索不起作用。我在这个演示中说明了这个问题stackblitz.com/edit/angular-auto-complete-eg-qmu7cn?file=app/…
  • 请问您有什么想法吗?
  • 请问您有什么想法吗?我真的需要你的帮助!
  • 等我解释一下

标签: angular typescript filter autocomplete


【解决方案1】:

也许不是最好的解决方案,但它确实有效。

所以问题是,在您添加更多字段后,表单数组的值开始如下所示:["3", "P"] 并且您的过滤器功能停止工作。

因此,如果您希望将跟踪表单值作为 Observable 保持您的方法,我已经制作了一个自定义管道来执行实际过滤。

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

@Pipe({
  name: 'myPipe'
})
export class MyPipe implements PipeTransform {

  transform<T>(value: string, list: T[], field: string, idx: number): T[] { 
    const filterValue = value[idx] ? value[idx].toString().toLowerCase() : '';
    return list.filter(state => state[field].toLowerCase().indexOf(filterValue) === 0);
  }

}

然后代替

*ngFor="let state of filteredStates | async

你使用管道

*ngFor="let state of filteredStates | async | myPipe: states : 'products_name': i"

它或多或少是通用的,所以它需要你的状态列表和一个要搜索的字段。

也在你的组件中替换

   this.filteredStates = this.myform.controls['products_id'].valueChanges
  .pipe(
    startWith(''),
    map(state =>  this._filterStates(state))
  );

   this.filteredStates = this.myform.controls['products_id'].valueChanges
  .pipe(
    startWith(['']),
  );

所以这种方式我们只是将值变化用作 Observable。 显然有些变量应该重命名。

就是这样。如果它不起作用,请发表评论,我错过了添加一些东西。

哦,是的 - 不要忘记将自定义管道添加到您的 AppModule 声明中

import { MyPipe } from './app/my-pipe.pipe';
...
declarations: [
    AutocompleteOverviewExample,
    MyPipe
],

【讨论】:

  • 我尝试过,但在我的代码中显示此错误:error TS2322: Type 'Observable&lt;string[]&gt;' is not assignable to type 'Observable&lt;State[]&gt;'. Type 'string[]' is not assignable to type 'State[]'. Type 'string' is not assignable to type 'State'.
  • 用这个做了一个 StackBlitz - 看起来很有效:stackblitz.com/edit/angular-auto-complete-eg-kccsao
  • 在这个filteredStates: Observable&lt;State[]&gt;;中显示错误
  • 你知道吗,为什么对我来说你的演示不起作用?
猜你喜欢
  • 2012-07-10
  • 2015-12-29
  • 2012-11-02
  • 1970-01-01
  • 2015-06-08
  • 2015-05-19
相关资源
最近更新 更多