我只是在学习angular 2,并且有一种情况,我要创建一个将成为一件设备的表格。与设备关联的 Realm 之一是建筑物。当用户编辑或添加新设备时,我希望向他们显示一个下拉列表,其中包含可以分配设备的建筑物列表。设备详细信息组件如下:
export class EquipmentDetailComponent implements OnInit {
equipment: IEquipment;
equipmentForm: FormGroup;
buildingList: Ibuilding[];
constructor(private EquipmentService: EquipmentService,
private BuildingsService: BuildingsService) { }
ngOnInit() {
this.equipment = this.EquipmentService.getEquipmentDetail(1);
this.buildingList = this.BuildingsService.getBuildingList();
let id = new FormControl(this.equipment.id);
let unit = new FormControl(this.equipment.unit);
let active = new FormControl(this.equipment.active);
let building = new FormControl(this.equipment.building.id);
this.equipmentForm = new FormGroup({
id: id,
unit: unit,
active: active,
building: building
})
}
saveEquipment(formValues){
console.log(formValues);
}
onSelect(id){
this.equipment.building = this.BuildingsService.getBuildingDetail(id);
console.log(this.equipment.building)
}
}
equipment-detail html如下:
<div class="col-md-2">
<form [formGroup]="equipmentForm" (ngSubmit)="saveEquipment(equipmentForm.value)" autocomplete="off" novalidate>
<div class="form-group">
<label form="unit">Unit:</label>
<input formControlName="unit" id="unit" type="text" class="form-control" placeholder="Unit...."/>
</div>
<div class="form-group">
<label form="active">Active:</label>
<input formControlName="active" id="active" type="checkbox" class="form-control"/>
</div>
<div class="form-group">
<label form="building">Building:</label>
<select class="form-control" formControlName="building" (change)="onSelect($event.target.value)">
<option *ngFor="let building of buildingList" value={{building.id}}>
{{building.buildingName}}
</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
当我单击下拉选项时,将得到一个代表所选建筑物的对象。结果是
Object {id: 2, buildingName: "Building 2", active: true}
active: true
buildingName: "Building 2"
id: 2
当我单击保存按钮并查看与formcontrol关联的数据时,建筑物不再是对象,而只是buildingId。
Object {id: 1, unit: "Item 1", active: true, building: "2"}
active: true
building: "2"
id: 1
unit:"Item 1"
__proto__: Object
如何获得要与建筑物对象一起设置的主要设备对象,而不仅仅是建筑物ID?
最佳答案
这是因为您具有building.id
的value属性,这就是为什么它在选项选择时分配building.id
的原因。您应该考虑使用整个value
对象将ngValue
属性绑定(bind)更改为building
。
<select class="form-control" formControlName="building" (change)="onSelect($event.target.value)">
<option *ngFor="let building of buildingList" [ngValue]="building">
{{building.buildingName}}
</option>
</select>