Helene
Helene

Reputation: 421

Filter on a mat-select

I need to filter data on a select because there is too much options. I did it like this :

        <mat-form-field>
          <mat-select placeholder="Unit.." (change)="onTabChange(element, $event.value.id, 'assignedUnit')">
            <input matInput type="text" (keyup)="filterListCareUnit($event.target.value)">
            <mat-option *ngFor="let careUnit of listCareUnits" [value]="careUnit">
              {{ careUnit.label }}
            </mat-option>
          </mat-select>
        </mat-form-field>

on key up, i'm calling filterListCareUnit($event.target.value)

but in this function i don't know to use the filter rxjs

I have my listCareUnits and I want to remove all object which don't contains the $event.target.value

for now I did this but clearly don't work, my list always contains the same items :

  filterListCareUnit(val) {
    console.log(val);
    this.listCareUnits.filter((unit) => unit.label.indexOf(val));
  }

Newbie at angular/rxjs .. Thanks for the help

Upvotes: 12

Views: 32431

Answers (3)

Amichay Turjeman
Amichay Turjeman

Reputation: 31

here a quick workaround without code in ts file

  <mat-select [(ngModel)]="result">
    <input matInput placeholder="filter.." #filterplc>
    <div  *ngFor="let opt of options ">
    <mat-option *ngIf="opt.includes(filterplc.value)"
                [value]="opt">
      {{opt}}
    </mat-option>
      </div>
  </mat-select>

Upvotes: 3

PLB
PLB

Reputation: 891

I know that this has been answered, but you could also have used "mat-select-filter".

https://www.npmjs.com/package/mat-select-filter

Hopefully this will help someone else.

Upvotes: 3

edkeveked
edkeveked

Reputation: 18381

You have to assign the returned filtered list.

 filterListCareUnit(val) {
    console.log(val);
    this.listCareUnits = this.listCareUnits.filter((unit) => unit.label.indexOf(val) > -1);
  }

But in order not to lose the data of your initial array, it will be better to use another array for processing that will always contain your initial set of data.

anotherArray = this.listCareUnits;
filterListCareUnit(val) {
        console.log(val);
        this.listCareUnits = this.anotherArray.filter((unit) => unit.label.indexOf(val) > -1);
      }

Upvotes: 12

Related Questions