Jezyk Danzowki Jezyk Danzowki - 4 months ago 65
AngularJS Question

angular 2 select options default value

I can't seem to work out how to easily set a value as the default value for a select dropdown list.

My current code

<select class="form-control" ngControl="modID" #modID="ngForm">
<option *ngFor="let module of modules" [value]="module._id">{{module.moduleName}}</option>
</select>


i have tried playing with the [selected] decorator but cannot work out how to get it to work.

given i have this modInst json object below:

{
"_id": 5,
"semester": "Tri 3",
"year": 2018,
"__v": 0,
"modID": [
{
"_id": 6,
"moduleLeader": "Jake Groves",
"moduleName": "Software Implementation",
"__v": 0
}
]
},


i would like the modInst.modID[0]._id to be selected from all the modules._id (modules) is whats populating the select list

any easy way of doing this?

edit:

i've tried adding
[selected]="module._id == modInst.modID[0]._id"
but i get no success on it making it the selected value

i've also tried
[ngValue]="modInst.modID[0]._id"
and it still doesn't select the module with id 6 in the list

one last addition ... i've tried a manual 'selected' and it still does not make a selected value upon load
[selected]="module._id == '7'"

Answer

You can use [(ngModel)] to do this.

<select [(ngModel)]="selectedModule">
     <option *ngFor="let module of modules" [value]="module._id">    {{module.moduleName}}/option>
   </select>

For example

import { Component } from '@angular/core';

@Component({
  selector: 'my-awsome-component',
  template: `
    <select [(ngModel)]="selectedModule">
     <option *ngFor="let module of modules" [value]="module._id">    {{module.moduleName}}/option>
   </select>
  `
})
export class MyAwesomeComponent {

modules: any[];
selectedModule: any = null;

loadModules(){
  //load you modules set selectedModule to the on with the
  //id of modInst.modID[0]._id you can either loop or use .filter to find it.

  }
}

Where you load the models from JSON in your component create a variable for the selectedModule and set the value equal to the module with the matching ID. See this answer here for an example of how to use ngModel on a select input:

Binding select element to object in Angular 2

Also selectedModule will reflect the value of the currently selected item if you need to enable / disable inputs etc based on a selection.

Comments