Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7: Clear selection with x-button on a dropdown box

I thought I can combine the examples from Angular for dropdown and the Input with clear box to:

<mat-form-field >
  <mat-select placeholder="Country" [(value)]="selectedCountry" (selectionChange)="emitItemChanges()">
    <div *ngFor="let item of lstItems|async">
      <mat-option *ngIf="addItem(item)" [value]="item">{{item.title}}</mat-option>
    </div>
  </mat-select>
  <button mat-button *ngIf="selectedCountry" matSuffix mat-icon-button aria-label="Clear" 
    (click)="selectedCountry=undefined">
    <mat-icon>close</mat-icon>
  </button>
</mat-form-field>

Which works close to the way as intended

enter image description here

which clears the input. The problem I'm facing now is that it immediately opens the selection box. Anyway how to prevent this behaviour?

I know there exists other solutions for clearing the selection. I want to know if this approach is possible?

like image 503
LeO Avatar asked Nov 30 '18 10:11

LeO


People also ask

How to clear selected value of dropdown in ANGULAR?

By clicking on the clear icon which is shown in DropDownList element, you can clear the selected item in DropDownList through interaction.

How do I remove the clear icon from Ng select?

In your stylesheet add display: none; to the . ng-clear-wrapper selector.

How do you assign a value to mat select?

Create Select using <mat-select> To add elements to select option, we need to use <mat-option> element. To bind value with <mat-option> , we need to use value property of it. The <mat-select> has also value property to bind selected value to keep it selected. We need to use <mat-select> inside <mat-form-field> element.


2 Answers

(click)="selectedCountry=undefined; $event.stopPropagation()" helped! Thx to @Sachila :-)

So the full code looks like:

  <button mat-button *ngIf="selectedCountry" matSuffix mat-icon-button 
    aria-label="Clear" (click)="selectedCountry=undefined; $event.stopPropagation()">
  <mat-icon>close</mat-icon>
like image 122
LeO Avatar answered Sep 20 '22 14:09

LeO


Example for Reactive Forms

$event.stopPropagation() - doesn't open select again

       <mat-form-field>
         <mat-select formControlName="team" placeholder="Team">
           <mat-option *ngFor="let team of availableTeams" [value]="team.id">{{team.name}}</mat-option>
         </mat-select>
         <button *ngIf="form.controls.team.value"
                 matSuffix
                 mat-icon-button
                 type="button"
                 aria-label="Clear"
                 (click)="form.controls.team.setValue(null); $event.stopPropagation()">
           <mat-icon>close</mat-icon>
         </button>
        </mat-form-field>
like image 28
Ania Avatar answered Sep 18 '22 14:09

Ania