简体   繁体   中英

How to add a clear icon on dropdown Angular Material?

I'm trying to add a clear icon on the right side of a dropdown (select component) in Angular material only if the user selects an option. If the user clicks on the "clear" icon I want to delete the value and reset the field. So far I have the dropdown and struggling on displaying the icon properly. Can anyone point me in the right direction? thanks in advance.

Here's my code:

<mat-form-field appearance="fill">
  <mat-label>Select a food</mat-label>
  <mat-select>
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
    <mat-select-trigger>
        <button>
           <mat-icon>clear</mat-icon>
       </button>
    </mat-select-trigger>
  </mat-select>
</mat-form-field>

Here's LIVE DEMO

You need to add ngModel on mat-select for two way binding to add selected value into it. Also add button as suffix of mat-select.

<mat-select [(ngModel)]="selectedFood">
    <mat-option *ngFor="let food of foods" [value]="food.value">
        {{ food.viewValue }}
    </mat-option>
</mat-select>
<button mat-button matSuffix *ngIf="selectedFood" mat-icon-button (click)="onClick($event)">
    <mat-icon>close</mat-icon>
</button>

On your component side you need to add following function to clear selected food value.

onClick(event: any) {
    this.selectedFood = "";
    event.stopPropagation();
}

event.stopPropagation() will stop mat select dropdown to be opened on cick of clean button.

Here is your working solution:

https://stackblitz.com/edit/angular-c7hgum-94nqyq

<mat-form-field appearance="fill">
    <mat-label>Select a food</mat-label>
    <mat-select [(ngModel)]="selectedFood">
        <mat-option *ngFor="let food of foods" [value]="food.value">
            {{food.viewValue}}
        </mat-option>
    </mat-select>
    <button mat-button *ngIf="selectedFood" matSuffix mat-icon-button aria-label="Clear" (click)="selectedFood=''">
    <mat-icon>close</mat-icon>
  </button>
</mat-form-field>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM