Loading episodes…
0:00 0:00

Angular Select Change Event

00:00
BACK TO HOME

Angular Select Change Event

10xTeam December 04, 2023 2 min read

The (change) event is used to handle changes in the selected option of a <select> element in Angular. When the user selects a different option, the (change) event emits an event object that contains the new selected value. You can then use this event object to update your component’s data or perform other actions.

Here is an example of how to use the (change) event in Angular:

<select (change)="onChange($event.target.value)">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
</select>
export class AppComponent {
  selectedOption: string = 'option1';

  onChange(newValue: string) {
    this.selectedOption = newValue;
    console.log(`Selected option: ${this.selectedOption}`);
  }
}

In this example, the onChange() method is called whenever the user selects a different option in the <select> element. The method updates the selectedOption property of the component with the new selected value, and then logs the new value to the console.

Here is another example of how to use the (change) event to perform an action based on the selected value:

<select (change)="onOptionChange($event.target.value)">
  <option value="option1">Display option 1 content</option>
  <option value="option2">Display option 2 content</option>
  <option value="option3">Display option 3 content</option>
</select>

<div id="optionContent">
  
</div>
export class AppComponent {
  optionContent: string = 'option1 content';

  onOptionChange(newValue: string) {
    switch (newValue) {
      case 'option1':
        this.optionContent = 'option1 content';
        break;
      case 'option2':
        this.optionContent = 'option2 content';
        break;
      case 'option3':
        this.optionContent = 'option3 content';
        break;
    }
  }
}

In this example, the onOptionChange() method is called whenever the user selects a different option in the <select> element. The method uses a switch statement to determine which option was selected and updates the optionContent property of the component with the corresponding content. The updated content is then displayed in the <div> element with the id optionContent.


Join the 10xdev Community

Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.

Audio Interrupted

We lost the audio stream. Retry with shorter sentences?