自动完成中的filterOptions不起作用

时间:2018-10-12 09:25:24

标签: angular typescript filter autocomplete

我有这个demo

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

我有以下过滤器代码:

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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

也许不是最好的解决方案,但是它正在起作用。

所以问题在于,添加更多字段后,表单数组的值开始看起来像这样:["3", "P"],并且过滤器功能停止工作。

因此,如果您希望保持跟踪表单值的方法为“可观察”状态,我已经制作了一个自定义管道来进行实际过滤。

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(['']),
  );

因此,通过这种方式,我们仅将值更改用作可观察值。 显然应该重命名一些变量。

就是这样。如果无法使用,请发表评论,我错过了添加内容的步骤。

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

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