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
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?
By clicking on the clear icon which is shown in DropDownList element, you can clear the selected item in DropDownList through interaction.
In your stylesheet add display: none; to the . ng-clear-wrapper selector.
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.
(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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With