如何从Angular Select中的* ngFor项绑定对象id?此时,select绑定与插值相同的值。

时间:2018-02-07 11:41:02

标签: angular

我有一个列表listSiteTriage。我想绑定到控制器选择的值。

  <select [(ngModel)]="selectedSite" (ngModelChange)="onChange()">
                  <option *ngFor="let site of listSiteTriage" >{{site.Intitule}}</option>
                </select>

控制器:

import { Component, OnInit, OnChanges, NgModule} from '@angular/core';

@Component({
 selector: 'xxx',
 templateUrl: './xxx.component.html',
 styleUrls: ['./xxx.component.scss']
 })
 export class Travaux implements OnInit , OnChanges {

 listSiteTriage: any[];
 site: any;


 } 
  onChange(){
  console.log(this.selectedSite);
  }
 }

2 个答案:

答案 0 :(得分:2)

删除[ngValue]

<select [(ngModel)]="site" (ngModelChange)="onChange()">
         <option *ngFor="let site of listSiteTriage" >{{site.Intitule}}</option>
  </select>

答案 1 :(得分:1)

您是iteratorngModel个变量都被命名为site,将其重命名为不同(例如selectedSite

<select [(ngModel)]="selectedSite" (ngModelChange)="onChange()">
      <option *ngFor="let site of listSiteTriage" [ngValue]="site.Id">{{site.Intitule}}</option>
</select>

import { Component, OnInit, OnChanges, NgModule} from '@angular/core';

@Component({
 selector: 'xxx',
 templateUrl: './xxx.component.html',
 styleUrls: ['./xxx.component.scss']
 })
 export class Travaux implements OnInit , OnChanges {

listSiteTriage: any[];
selectedSite: any = 1;

onChange(){
      console.log(this.site);
  }
}