角度(2)材质自动完成自定义过滤器

时间:2018-10-29 17:13:42

标签: angular angular2-forms angular-material-6

非常感谢您的帮助。

因此,目前我正在根据字符串值过滤搜索结果列表,例如,我有一个ngFor,它获取诸如“产品名称1”,“产品名称2”等字符串的列表。没有问题的项目列表,仅拼接我们键入的值。但是我需要做的是根据关键字字符串过滤掉这些名称。

例如,“产品名称1”是名称,它的关键字是“产品一产品Active Directory帮助台”,如果关键字包含字符串的任何部分,那么我只需要显示产品名称,在此示例中,“产品名称1”(基于这些关键字)。 (希望这是有道理的,下面的代码)

当前,列表是根据字符串是否匹配来过滤的,例如,如果我开始输入“ prod”,则将出现以“ prod”开头的所有内容。但是我需要做的是基于它,如果一个字符串包含该文本,那么例如,假设我们再次开始输入“ prod” ....并且在我的数组中,我有一个字符串,上面写着“ product 1 active directory etc”。 “我希望它以此来找到它,但是如果我输入活动目录,它也必须工作

products.component.ts:

  ngOnInit() {

    // proudct is an input field shown below
      this.filteredProducts = this._form1.controls['product'].valueChanges
      .pipe(
        startWith<string | Product>(''),
        map(value => typeof value === 'string' ? value : value.name),
        map(name => name ? this._filter(name) : this.products.slice())
      );

  }

  // Display the result in the dropdown list
  displayFn(product?: Product): string | undefined {
    return product ? product.name : undefined;
  }

  // Filter through the list of items
  private _filter(name: string): Product[] {
    if(name) {

      const filterValue = name.toLowerCase();

      return this.products.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0);
    }
  }

product.component.html:

<form [formGroup]="_form1" (ngSubmit)="_onFirstSubmit()" class="step-container">

    <mat-form-field class="mat-full-width-container">
      <input type="text" placeholder="Product or service name" aria-label="product" matInput formControlName="product" [matAutocomplete]="auto" (input)="prodChanged()" (blur)="selectProduct()">
      <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
        <mat-option *ngFor="let product of filteredProducts | async" [value]="product">
          {{ product.name }}
        </mat-option>
      </mat-autocomplete>
    </mat-form-field>

</form>

请帮助我尝试了一些似乎无法实现的事情,谢谢

1 个答案:

答案 0 :(得分:0)

尝试更改此行:

return this.products.filter(option => 
 option.name.toLowerCase().indexOf(filterValue) >= 0);
相关问题