How to set mat select value dynamically

To set the value of a mat-select dynamically, you can use the property ‘value’ which is bound to a variable in your component’s TypeScript code. Here’s how you can do it:

    
      <mat-select [(value)]="selectedValue">
        <mat-option value="option1">Option 1</mat-option>
        <mat-option value="option2">Option 2</mat-option>
        <mat-option value="option3">Option 3</mat-option>
      </mat-select>
    
  

In the above code, we are binding the ‘value’ property of the mat-select element to the ‘selectedValue’ variable in our component’s code. To set the value dynamically, you can update the ‘selectedValue’ variable with the desired option value.

For example, in your component’s TypeScript code:

    
      selectedValue: string = 'option2';

      // Function to change the select value dynamically
      changeSelectValue() {
        this.selectedValue = 'option3';
      }
    
  

In the above code snippet, we have initialized ‘selectedValue’ with ‘option2’ which will be the initially selected value. The ‘changeSelectValue’ function demonstrates how to dynamically change the selected value to ‘option3’.

You can bind the ‘changeSelectValue’ function to a button click or any other event to update the select value dynamically. For example:

    
      <button (click)="changeSelectValue()">Change Value</button>
    
  

Leave a comment