Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unselect selected option in md-select Angular2

In material2 when a select is initialized no default value is selected. If user selects a value he can't unselect it. I want to enable the user to unselect the value.

Plunkr

I went through the help already available but wasn't able to use it.

<mat-select id="formal"  formControlName="formal" placeholder="Default - No value selected">
   <mat-option value="1">formal</mat-option>
   <mat-option value="2">informal</mat-option>
</mat-select>
like image 556
Mahin Khan Avatar asked Feb 02 '17 15:02

Mahin Khan


2 Answers

What about using a method of matSelect.

<mat-select (selectionChange)="onChange($event)">
onChange(event: MatSelectChange) {
    const matSelect: MatSelect = event.source;
    matSelect.writeValue(null);
    // ...
}
like image 137
Sébastien Richez Avatar answered Oct 12 '22 00:10

Sébastien Richez


I ended up using ngModel and setting that value to undefined to get the required result.

<md-select id="formal" [(ngModel)]="selectedValue" formControlName="formal" placeholder="Default - No value selected">
    <md-option value="1">formal</md-option>
    <md-option value="2">informal</md-option>
 </md-select>

<div  (click)="unselect()">click me to clear md select</div>

In the Component

unselect(): void {
   this.selectedValue = undefined;
}

plunkr for the answer.

like image 27
Mahin Khan Avatar answered Oct 12 '22 01:10

Mahin Khan