How to reset the Custom Filter in Material Autocomplete with groups of options

时间:2017-12-18 06:34:12

标签: angular autocomplete angular-material2 angular5

How can I Reset the custom filter value in material autocomplete autocomplete. I have select input with the group of option like here. Now I want to create a custom filter which filter our result and it's option group name. Like In my ts file I have:

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'
      ]
    }]

Now In my 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>

My Typescript File:

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;
  }

The filter work fine but when I press backspace or deletes the keyword then it should reset my all value. Which is not working.

1 个答案:

答案 0 :(得分:0)

我没有经过测试但是你可以这样试试。另请查看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;
  }