Search code examples
angularangular-forms

Angular 11 - select first item in a dropdown list


simple thing; I want the first item in a dropdown list (mat-select) to be automatically selected when page loads.
This code below is my best guess but doesn't work, I still see an empty text, I have to dropdown and select first item manually. Do you know why or how to fix it? Thank you.

    <mat-form-field>
        <mat-label>Title</mat-label>
        <mat-select [(ngModel)]="selectedTitle" [(value)]="titleList[0].titleval">
            <mat-option *ngFor="let singleTitle of titleList" [value]="singleTitle.titleval">
                {{singleTitle.titletxt}}
            </mat-option>
        </mat-select>
    </mat-form-field>

Solution

  • Let angular do it for you

    In your TS file e.g in your ngOnInit()

    this.selectedTitle = this.titleList[0].titleval
    

    and your html

    <mat-form-field>
        <mat-label>Title</mat-label>
        <mat-select [(ngModel)]="selectedTitle">
            <mat-option *ngFor="let singleTitle of titleList" [value]="singleTitle.titleval">
                {{singleTitle.titletxt}}
            </mat-option>
        </mat-select>
    </mat-form-field>
    

    angular will select the first item for you