1
votes

What I'm using

  • angular
  • firebase
  • Currently, a standard HTML select component

What I'm trying to achieve

  • When a user is filling out some details in some inputs, I have a drop down containing a number of options

  • I want to have a default option selected (not a placeholder, an actual selection)

Question

  1. As I'm looping through an array (ngFor), how do I apply a 'selected' attribute to one of the options? Let's say for example that the array contained 'album 1', 'album 2'and 'album 3'. By default, I want 'album 2' to be automatically selected.

<select #selectedAlbum>
<option *ngFor="let album of albumList" [value]="folder.folder_title">{{album.album.title}}</option>
</select>
2

2 Answers

2
votes

You can bind your select element to an ngModel and then on the initialisation of your component set the ngModel to be your desired default value and the option will be selected for you by the two way binding provided by ngModel.

i.e.:

<select #selectedAlbum [(ngModel)]="mySelectedItem">

and in your component:

 mySelectedItem: string;

  ngOnInit() {
    this.mySelectedItem = 'album 2';
  }
0
votes

You can add a selected attribute:

example using a predefined item

<select #selectedAlbum>
<option *ngFor="let album of albumList" [value]="folder.folder_title" [selected]="ablum.ablum.title === 'album 2'">{{album.album.title}}</option>
</select>

example using an index

<select #selectedAlbum>
<option *ngFor="let album of albumList; let i = index;" [value]="folder.folder_title" [selected]="i === 1">{{album.album.title}}</option>
</select>

Note:

This method does not use two-way binding. This is a one-way binding as you currently have implemented. If you'd prefer to use two-way binding (which is much more elegant in general) I'd highly recommend digging deeper into form models.