Angular Material Component List, does not report initial selection

133 Views Asked by At

In a HTML like this:

<mat-selection-list #contactsList [(ngModel)]="selectedContact"  [multiple]="false" hideSingleSelectionIndicator="true">
      <mat-list-option *ngFor="let contact of contactsList; index as i; first as isFirst" color="primary" [value]="contact" [selected]="isFirst" >
        <mat-icon matListItemIcon class="mat-list-item-icon">{{contactClassIcons[contact.contact_types_id!]}}</mat-icon>
        <div matListItemTitle class="profile-line-primary">
          {{contact.contact_typeclass_title}}
      </div>
      <div matListItemLine class="profile-line-secondary">
        {{contact.contact_info}}
    </div>
      </mat-list-option>
    </mat-selection-list>

Angular 15.2.0, on Windows 11/ WSL2 platform I need to get a trigger about the item that is actually selected during the initiation.

I tried the following:

  1. use (selectionChange)='onSelectionChanged($event)' but never triggered using the code above
  2. use (ngModelChange)='onSelectionChanged($event)' triggered but returned empty array []
  3. use [(ngModel)]='selectedContact' used set/get property and initial call was empty array []

after initial rendering, it shows that the first option is actually selected, and if I click on any of the options in the list, all events triggered, the code works normally as expected with all 3 options above, the only problem is how to catch the initial selected option that is done during initiation? I can think of an option to sneak on the original list and capture the first item, but that's not what I am looking for

1

There are 1 best solutions below

0
On

The selection is a 2-way binding of selectedContacts. The property [selected] contrasts the model by determining the selected item otherwise.

You should remove the [selected] property from the list options, and initialize your mode selectedContcats instead.

Here is excerpt from an example I created here.

Markup

<mat-selection-list multiple="false" [(ngModel)]="selectedItems"  (selectionChange)="onSelectionChanged($event)">
  <mat-list-option *ngFor="let item of items" [value]="item">
    {{ item }}
  </mat-list-option>
</mat-selection-list>

Class

export class App implements OnInit {
  name = 'Angular';
  items = ['me', 'you', 'him', 'her'];
  selectedItems = ['him'];

  ngOnInit(): void {
    console.log('ngOnInit:', this.selectedItems);
  }

  onSelectionChanged(event: MatSelectionListChange): void {
    console.log('New selection:', this.selectedItems);
  }
}