How to unselect selected option in md-select Angular2

If you are using angular forms, you can always patchValue to '' as like below.

First, the select element. This example is using Ionic, but it's the same as Angular.

<ion-select formControlName="formal" item-start>
   <ion-option *ngFor="let option of input.options" value="{{option}}">{{option}}</ion-option>
</ion-select>

<ion-icon color="danger" name="close" (click)="unselect('formal')" item-end></ion-icon>

Where form is a FormGroup.

  form: FormGroup;

And the unselect method patches a null value.

  unselect(id: string): void {
    let reset = {};
    reset[id] = ''
    this.form.patchValue(reset);
  }

Best regards!


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.


What about using a method of matSelect.

<mat-select (selectionChange)="onChange($event)">
onChange(event: MatSelectChange) {
    const matSelect: MatSelect = event.source;
    matSelect.writeValue(null);
    // ...
}

I have another solution that I think worth to mention it: add an empty <md-option> and reset the <md-select> on its click

  <md-select id="formal" formControlName="formal" placeholder="Default - No value selected">
      <md-option (click)="form.controls.formal.reset()"></md-option>
      <md-option value="1">formal</md-option>
      <md-option value="2">informal</md-option>
  </md-select> 

this way you don't need any custom code in your Component neither use ngModel

see Plunker