Sergio Cano
Sergio Cano

Reputation: 760

Loading a default option in a select with angular

I am trying to put a default option in my select that comes from a service.

My Select.

<select (change)="changeValue()" [(ngModel)]="selectedValue">
<option *ngFor="let item of items" [ngValue]="item">{{ item.article }} - {{ item.value }}</option>
</select>

The array that I am passing to the ngFor.

  items: Array<any> = 
  [{ article: 'item1', value: 10 },{ article: 'item2', value: 20 }]

When I load this component in my app, I receive from the database an object that contains one of these options.

So what I would like to do is, the option that I receive, set it as default.

I tried with [selected] but it is not working. How can I do it?

Upvotes: 4

Views: 4684

Answers (2)

User3250
User3250

Reputation: 3421

A non ngModel way of doing it is as below, as ngModel is deprecated in v7: https://next.angular.io/api/forms/FormControlName#use-with-ngmodel

<select (change)="changeValue()" [value]="defaultValue">
<option *ngFor="let item of items" [value]="item.value">{{ item.article }} - {{ item.value }}</option>
</select>

Demo here: https://stackblitz.com/edit/angular-wvnjn5

Upvotes: 2

Just code
Just code

Reputation: 13801

Basically you have this things missing:

  1. ngValue should be item.value
  2. You already assingning values so just changing the selectedValue variable would work, just like I did inside ngOnInit

Try something like this:

Typescript end:

  items: Array<any> =
    [{ article: 'item1', value: 10 }, { article: 'item2', value: 20, defaultSelected: true }];
  selectedValue: string = '';
  ngOnInit() {      
    this.selectedValue = this.items.filter(a => a.defaultSelected)[0].value;
  }

HTML end:

<select (change)="changeValue()" [(ngModel)]="selectedValue">
<option *ngFor="let item of items" [ngValue]="item.value">{{ item.article }} - {{ item.value }}</option>
</select>

Please check this demo: https://stackblitz.com/edit/angular-v2a81r

Upvotes: 4

Related Questions