0

I wanna know how to make default select the first item of mat-list in angular. I tried but not able to resolve it. My mat-list code is here

export class StationsListComponent implements OnInit {

  @Input() stations: Stations[];
  selectedStation: Stations;

  constructor() { }

  ngOnInit(): void {
    this.selectedStation = this.stations[0];
  }
}
<mat-list role="list">
  <div *ngFor="let book of Books">
    <mat-list-item id="{{book.bookId}}" role="listitem" class="list-item" routerLink="/home/{{book.bookId}}" [routerLinkActive]="['is-active']">
      <div class="station-div">
          <div class="station-name">{{book.bookName}}</div>
          <div class="station-location">{{book.authorName}}</div>
      </div>
    </mat-list-item>
  </div>
</mat-list>
0

2 Answers 2

9

You could use a 'mat-selection-list' and specify which entry you want to be selected by default by editing the [selected] value:

<mat-selection-list #itemList>
    <mat-list-option *ngFor="let item of items, let i = index" [selected]="item && i == 0">
      #{{i+1}} {{ item.name }}
    </mat-list-option>
</mat-selection-list>

In this case the first item would be selected by default, because [selected]="item && i == 0". If you change "i == 0" to "i == 1" the second item is selected an so on.

2
  • 2
    Meanwhile the accepted answer is good enough for experienced devs, I would much rather prefer this answer. Just because there is a working code sample showing how it works. Thank you Gereon99. Now, take my upvote. Dec 12, 2020 at 5:01
  • This is the best answer and I agree that should be marked as accepted
    – Davide
    Jan 7, 2021 at 11:52
2

According to the Angular Material Docs, mat-list-item doesn't have a selected input property that you can apply to the element. however mat-list-option does.

as such, if you switch to using mat-list-option you can leverages properties [selected] and [value]

1
  • so what should I use can give me a demo code. and Thankyou :)
    – Md Enayat
    Jul 13, 2020 at 7:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.