openedChange vs selectionChange in mat-select




Asked on May 15, 2024
What is difference between openedChange and selectionChange in Angular Material mat-select?


Replied on May 15, 2024
1.
openedChange event emits when a user opens a panel or close it. It means to select an item from select dropdown, openedChange event will emit two times, one for opening panel and second for closing panel.

2.
selectionChange event emits when a user selects a value.

Suppose I have a select dropdown using mat-select as below.
HTML code:

<mat-form-field>
  <mat-label>Select Item</mat-label>
  <mat-select [formControl]="item"
  (openedChange)="onOpenedChange()"
  (selectionChange)="onSelectionChange()">
    <mat-option value="a">A</mat-option>
    <mat-option value="b">B</mat-option>
    <mat-option value="c">C</mat-option>
  </mat-select>
</mat-form-field>

TS code:

item = new FormControl('');
onOpenedChange() {
  console.log('---onOpenedChange---');
}
onSelectionChange() {
  console.log('---onSelectionChange---');
}

For openedChange event, onOpenedChange() method will execute.

For selectionChange event, onSelectionChange() method will execute.

If I select, item B from select dropdown, in console we will get output as below.

---onOpenedChange---
---onSelectionChange---
---onOpenedChange---

We observer that for selecting one item,  onOpenedChange() method executes two times whereas onSelectionChange() executes only one time.



Write Answer












©2024 concretepage.com | Privacy Policy | Contact Us