Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度2使用“选择”选项保留选定对象的值_Angular_Angular2 Template - Fatal编程技术网

Angular 角度2使用“选择”选项保留选定对象的值

Angular 角度2使用“选择”选项保留选定对象的值,angular,angular2-template,Angular,Angular2 Template,每种植物都有一个plantid、plantname和角色。我试图从选项选择中恢复对象的整体 onChange(newValue){ console.log(newValue) this.selectedPlant=newValue } {{plant.plantname} 如果我将[value]=“plant”,我会得到“[Object,Object]”。我将编写一个服务来从另一个值中获取一个值,但我觉得应该有一种更干净的方法来实现这一点 如果您想要整个plant对象,而不需要更改大部分代

每种植物都有一个plantid、plantname和角色。我试图从选项选择中恢复对象的整体

onChange(newValue){
console.log(newValue)
this.selectedPlant=newValue
}

{{plant.plantname}

如果我将
[value]=“plant”,我会得到“[Object,Object]”
。我将编写一个服务来从另一个值中获取一个值,但我觉得应该有一种更干净的方法来实现这一点

如果您想要整个plant对象,而不需要更改大部分代码,您可以这样做-

onChange(plantid){
  console.log(plantid)
  this.selectedPlant = this.plants.filter((plant)=>{ return plant.plantid=== plantid;});
}
在你的html中-

<select *ngIf="plants" class="form-control" style="width:auto;" #sel (ngModel)]="selectedPlant" (ngModelChange)="onChange($event.target.value)"> 
<option *ngFor="#plant of plants" [value]="plant.plantid">{{plant.plantname}}</option>

{{plant.plantname}


希望能有所帮助。

如果您想使用对象作为值而不是普通字符串,则必须使用
[ngValue]
而不是
[value]


{{plant.plantname}