v_char
v_char

Reputation: 155

Reset a mat-select value by clicking a button

I have a mat-select dropdown for filtering data on the UI. I emit the data from the child component to the parent component with the getTeam function

Mat-Select

<mat-form-field>
  <mat-label>Select Team</mat-label>
  <mat-select (selectionChange)="getTeam($event)">
    <mat-option *ngFor="let team of teams" [value]="team.name">
      {{team.name}}
    </mat-option>
  </mat-select>
</mat-form-field>
<span class="material-icons" (click)="reset()">delete_sweep</span>

Filter logic (.ts) The getTeamQuery receives the emitted value and filters the UI data.

  videos: Video[] = videos;
  filteredVideos: Video[] = videos;

    getTeamQuery(queryEmitted: string) {
    this.videos = this.filteredVideos.filter(video => {
      return video.team === queryEmitted;
    });
  }


  **Clearing the filter selection**

  reset() {
    this.videos = videos;
  }

How can I reset the selection of the mat-select and return to the initial state, by clicking the material icon? Initial state, meaning the state where the mat-select value is the placeholder.

Upvotes: 5

Views: 34038

Answers (2)

Swati Dubey
Swati Dubey

Reputation: 1

interface measurement {
  value: string;
  viewValue: string;
}
export class SelectOverviewExample {
 RemoveDefaultSelectValue : any;
 
  measurements: measurement[] = [
      {value: 'LineString', viewValue: 'Line String'},
      {value: 'Polygon', viewValue: 'Area'},
  ];
}
onFunChange = function(value){
    let valv = this.value;
    this.RemoveDefaultSelectValue = valv;
    $("#stopmesrment").on('click', () =>{
      this.RemoveDefaultSelectValue = {};
    });
  }
<mat-form-field appearance="outline">
   <mat-label>Measurement</mat-label>
     <mat-select (selectionChange)="onFunChange($event)"      [value]="RemoveDefaultSelectValue" id="type" placeholder="Select Measurement" #MeasurementValue>
  <mat-option *ngFor="let measurement of measurements [value]="measurement.value">{{measurement.viewValue}}</mat-option>
  </mat-select>
</mat-form-field>
                        
                        
<button id="stopmesrment" type="button" class="btn btn-secondary btn-sm">clear measurement</button>

Upvotes: -1

Piash
Piash

Reputation: 1131

Just add a normal mat-option before the loop, like following:

<mat-select (selectionChange)="getTeam($event)">
    <mat-option value="">Select a name...</mat-option>

    <mat-option *ngFor="let team of teams" [value]="team.name">
      {{team.name}}
    </mat-option>

  </mat-select>

EDIT: as per your comment, you can use ngModel for this case, like following:

html file:

<mat-select (selectionChange)="getTeam($event)" [(ngModel)]="teamInitial">
  // your code...
</mat-select>

ts file:

export class YourComponent {
   teamInitial = '';

   // you code...

   reset() {
     this.teamInitial = '';
   }
}

Upvotes: 10

Related Questions