1

I have a mat-select. when I first show the form I want it to select the first item in the select after the data is loaded. How can I do this?

  <mat-select 
          placeholder="period"
          (selectionChange)="selectperiod($event)"
          (ngModel)="(periodoptions)"
        >
          <mat-option
            *ngFor="let p of periodoptions | async"
            [value]="p.periodid"
          >
            {{ p.periodstart }}
          </mat-option>
        </mat-select>

using this to call function to pull rest data

 of(this.getperiods()).subscribe(pp => {
      this.periodoptions = pp;
user13520940
  • 133
  • 2
  • 7
  • I think you should look at this answer. https://stackoverflow.com/questions/50650790/set-default-option-in-mat-select – lastSheep Jul 02 '20 at 00:56

2 Answers2

0

If you want to use ngModel, just replace (ngModel) by [(ngModel)]. You can also replace the ngModel by [(value)] to avoid using the ngModel module.

Also, assign periodoptions to the ngModel is wrong if you want to select the first item of the array, since each mat-option value is p.periodid. You will have to use periodoptions[0].periodid instead

-1

Maybe this can help you:

<mat-select placeholder="period" (selectionChange)="selectperiod($event)" [(ngModel)]="periodoptions">
    <mat-option>Default Option</mat-option>
    <mat-option *ngFor="let p of periodoptions | async" [value]="p.periodid">
        {{ p.periodstart }}
    </mat-option>
</mat-select>
Gabriel Martins
  • 537
  • 4
  • 12