Topic: Pre Select first item in mdb-select

Declan Ward priority asked 5 months ago


Expected behavior

The list is populated with an array of objects.

      <mdb-select  
          (valueChange)="onMonthClick($event)" 
          >
            <mdb-option *ngFor="let yearMonth of yearMonths"  [value]="[yearMonth.Date]">
              {{yearMonth.Date | date:'MMM yyyy' }} 
              <span *ngIf="includecount">({{ yearMonth.DocumentCount }} )</span>
            </mdb-option>
          </mdb-select>

I would like to, on load, effectively click the first item in the list and fire the valueChange event.

Actual behavior

I can achieve this with

this.onMonthClick(this.yearMonths[0].Date);

My difficulty is that the selection is not displayed.

Resources (screenshots, code snippets etc.)

This is the result.

enter image description here

This is what I want to achieve

enter image description here

I have tried setting selectedValue as per docs without success.

Define selectedValue

    selectedValue = new FormControl();

HTML

      <mdb-select  [formControl]="selectedValue"
          (valueChange)="onMonthClick($event)" 
      >

And when the data is loaded for the select:

 this.selectedValue = new FormControl(this.yearMonths[0].Date);

Rafał Seifert staff commented 5 months ago

Could you edit your post and provide full code sample how your not working code is currently set up? We could not recreate your problem. Adding the : this.selectedValue = new FormControl(this.yearMonths[0].Date); to ngOnInit works good in our demo example.


Declan Ward priority answered 5 months ago


Thank you Rafal.

I have found the problem:

<mdb-option *ngFor="let yearMonth of yearMonths"  [value]="[yearMonth.Date]">

should be

<mdb-option *ngFor="let yearMonth of yearMonths"  [value]="yearMonth.Date">

I had [] around yearMonth.Date :(



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Resolved

Specification of the issue

  • ForumUser: Priority
  • Premium support: Yes
  • Technology: MDB Angular
  • MDB Version: MDB5 5.1.0
  • Device: All
  • Browser: All
  • OS: Windows
  • Provided sample code: No
  • Provided link: No