在angular2中选择一个默认对象

时间:2017-04-28 10:30:47

标签: typescript angular2-forms

我正在尝试在下拉列表中选择默认值。这里的值是一个对象而不是一个字符串。使用字符串,以下方法工作正常。我尝试使用对象时遇到问题。

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

@Component({
  selector: 'awesome-component',
  template: `
    <select [(ngModel)]="selectedModule">
     <option *ngFor="let module of modules" [ngValue]="module">{{module.moduleName}}</option>
   </select>
  `
})
export class AwesomeComponent implements OnInit {

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

  ngOnInit(){
    this.loadModules();
  }

  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.
      this.modules = [];
      this.modules.push({moduleName:'Ford',_id:1});
      this.modules.push({moduleName:'Chevy',_id:2});
      this.modules.push({moduleName:'Honda',_id:3});
      this.modules.push({moduleName:'Toyota',_id:4});

      this.selectedModule = {moduleName:'Toyota',_id:4};
    }
}

0 个答案:

没有答案