代码之家  ›  专栏  ›  技术社区  ›  Sonu

如何使用选项组重置“材质自动完成”中的自定义过滤器

  •  0
  • Sonu  · 技术社区  · 8 年前

    如何在“材质自动完成”中重置自定义过滤器值 autocomplete . 我选择了如下选项组的输入 here . 现在,我想创建一个自定义过滤器,用于过滤结果及其选项组名称。就像在我的ts文件中一样,我有:

    pokemonGroups = [
        {
          name: 'Grass',
          pokemon: [
            'bulbasaur-0', 'Bulbasaur', 'oddish-1','Oddish','bellsprout-2', 'Bellsprout'
          ]
        },
        {
          name: 'Water',
          pokemon: [
            'squirtle-3', 'Squirtle', 'psyduck-4','Psyduck', 'horsea-5', 'Horsea'
          ]
        }]
    

    现在在我的html中:

    <form [formGroup]="searchForm">
      <mat-form-field class="example-full-width">
        <input type="text" placeholder="Pokemon" aria-label="Pokemon" matInput formControlName="pokemonControl" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete">
          <mat-optgroup *ngFor="let group of pokemonGroups" [label]="group.name" [disabled]="group.disabled">
            <mat-option *ngFor="let poke of group.pokemon" [value]="poke">
              {{ poke }}
            </mat-option>
          </mat-optgroup>
        </mat-autocomplete>
      </mat-form-field>
    </form>
    

    我的Typescript文件:

    ngOnInit() {
    // ... code
    this.searchForm.controls.pokemonControl.valueChanges
          .subscribe(
          (val) => {
            this.filter(val);
          }
          );
    }
    filter(val) {
        for (const pokemon of this.pokemonGroups) {
          pokemon.pokemon= pokemon.pokemon.filter(pok=>
            pok.toLowerCase().indexOf(val.toLowerCase()) === 0);
        }
    
        return this.pokemonGroups;
      }
    

    过滤器工作正常,但当我按backspace或删除关键字时,它应该重置我的all值。这不起作用。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Aman Kumar    8 年前

    我还没有测试过,但你可以这样试试。也请检查 this

    ngOnInit() {
    
    this.pokemonControl.valueChanges
          .subscribe(
          (val) => {
            this.filter(val);
          }
          );
    }
      filter(val) {
    
        for (const pokemon of this.pokemonGroups) {
          pokemon.pokemon= pokemon.pokemon.filter(pokemon=>
            pokemon.toLowerCase().indexOf(val.toLowerCase()) === 0);
        }
        return this.pokemonGroup;
      }
    
    推荐文章