Home > OS >  What is the cleanest way to reset a Material Angular select's value to its label from typescrip
What is the cleanest way to reset a Material Angular select's value to its label from typescrip

Time:01-19

I'd like to get rid of the value of this select, and set it back to Select Member in the typescript when an internal event occurs. I haven't found a good way to do this on the typescript side. Any suggestions?

<mat-form-field appearance="fill">
<mat-label>Select Member</mat-label>
<mat-select (selectionChange)="getAthleteAnalytics($event.value)" id="member-select">
    <mat-option *ngFor="let member of members" [value]="member.id">
        {{member.firstName}} {{member.lastName}}
    </mat-option>
</mat-select>
</mat-form-field>

CodePudding user response:

first of all it is better to use ReactiveForms in your case, but anyway you can still work like this

<mat-form-field appearance="fill">
  <mat-label>Select Member</mat-label>
  <mat-select
    #model="matSelect"
    (selectionChange)="getAthleteAnalytics(model)"
    id="member-select"
  >
    <mat-option *ngFor="let member of members" [value]="member.id">
      {{ member.firstName }} {{ member.lastName }}
    </mat-option>
  </mat-select>
</mat-form-field>

and here is the code of component ts file


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular '   VERSION.major;

  latestSelectedValue :number |undefined;

  members = [
    {id: 1 , firstName:"Ahmed" , lastName:"Mostafa"},
    {id: 2 , firstName:"Mohamed" , lastName:"Mostafa"},
    {id: 3 , firstName:"Ebrahem" , lastName:"Mostafa"},
    {id: 4 , firstName:"Hba" , lastName:"Mostafa"},
  ]

  getAthleteAnalytics(model: MatSelect): void {
    // here you got the selected value   
    this.latestSelectedValue = model.value;
    // if you want to reset the select after that just make the value null or undefined 
    // im calling an mehtod to do that for me 
    // i wrap it inside timeout to show you the selcted value first on the control then after 3 seconds will reset it to null
    setTimeout(()=>{
      this.resetSelection(model)
    },3000)
    
  }

  resetSelection(select: MatSelect){
    select.value = null;
  }
}

also if you want the full example here is stackblitz click here

  • Related