Arsalan Khalid
Arsalan Khalid

Reputation: 256

Default select value for dropdown is not straight forward in Angular 7

I've been working with Angular 7 recently, and finding some strange stuff happening when trying to display a dropdown list, and showing a default value within this list. Here are two separate lists respectively:

sample.component.html

 <select [(ngModel)]="organization" id="organization" required>
          <option *ngFor="let organization of organizations" [value]="organization.id" [ngValue]="organization.name">{{organization.name}}</option>
        </select>
        <br>

I find that the above code displays the following in my browser:

enter image description here

Notice how the default value is set in the above, but in the next drop down the default value isn't set:

sample.component.html

<select [(ngModel)]="seniorExperience" id="seniorExperience" required>
          <option *ngFor="let seniorExperience of seniorExperiences" [value]="seniorExperience.seniorExperienceId" [ngValue]="seniorExperience.seniorExperienceName">{{seniorExperience.seniorExperienceName}}</option>
        </select>

The browser displays the following:

enter image description here

Why is the second dropdown not populated with the a default, whilst following the same syntax? From searching and reading docs I presumed that [ngValue] sets the default value of the dropdown, which seems to work for the first dropdown. Is there a better way to set the default select?

Upvotes: 1

Views: 10268

Answers (1)

Nadim Hossain Sonet
Nadim Hossain Sonet

Reputation: 1709

As per Angular 7 implementation:

In HTML:

<select *ngIf="ownerLevels" [value]="selectedOwnerLevel" (change)="onChangeOwnerLevel($event.target.value)" formControlName="ownerLevel" id="ddOwnerLevel">
   <option [value]="0" disabled>Select Owner Level</option>
   <option *ngFor="let ownerLevel of ownerLevels" [value]="ownerLevel.id">{{ownerLevel.name}}</option>
</select>

In TS:

ownerLevels = [
   { id: 1, name: 'Company' },
   { id: 2, name: 'Department' },
   { id: 3, name: 'Personal Area' }
];

selectedOwnerLevel: number = 0;

onChangeOwnerLevel(ownerLevelId: number) {
   this.selectedOwnerLevel = ownerLevelId;
}

Upvotes: 4

Related Questions