Search code examples
angularhtml-selectangular2-forms

Angular2 Selected item on dropdown not displaying


I have been going through all posts here and still I cannot it working. I am trying to implement a dropdown in Angular2 which shows at first a selected value.

HTML.

<div class="col-sm-8">
  <div class="form-group">
     <select [(ngModel)]="selectedProjectType" class="form-control" required name="projectType">
     <option *ngFor="let projectType of projectTypes"> {{projectType.name}}</option>
      </select>
       <p *ngIf="selectedProjectType">{{selectedProjectType.projectType}}</p>
     </div>
 </div>

Controller

selectedProjectType: ProjectType;

constructor(
private projectsService: ProjectsService){
this.project = new Project();
this.route.params
  .subscribe((params: Params) => { 
    this.projectsService.getProject(params['id']).then((project) => {
    this.project = project;
    this.selectedProjectType = project.projectType;
  });
 });}

The paragraph shows the correct selected project type while the select shows the first option. So I'm guessing I have assigned it right but I am having a problem in putting it as selected value for the select. I'm a beginner at Angular2 and I cannot find what I'm doing wrong. Thank you for the help.


Solution

  • If the value is not a string, use [ngValue]="..." on <option>:

    <option *ngFor="let projectType of projectTypes" [ngValue]="projectType">
      {{projectType.name}}
    </option>