Angular Select Change Event

Angular Select Change Event

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.