我正在学习角度2并且有一个案例,我正在创建一个将成为一件装备的表格。与设备相关的一个领域是建筑物。当用户正在编辑或添加新设备时,我希望它们能够显示一个下拉列表,其中包含可以将设备分配到的建筑物列表。设备详细信息组件如下:
$testVariable = "test";
function testFunction() {
global $testVariable;
}
设备详细信息html如下:
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)
}
}
当我点击下拉选项时,我得到一个代表我选择的建筑物的对象。结果是
<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>
当我单击保存按钮并查看与formcontrol关联的数据时,建筑物不再是对象,它只是buildingId。
Object {id: 2, buildingName: "Building 2", active: true}
active: true
buildingName: "Building 2"
id: 2
如何使用建筑物对象而不仅仅是建筑物ID来设置主设备对象?
答案 0 :(得分:4)
这是因为您拥有building.id
的值属性,这就是它为选项选择分配building.id
的原因。您应该考虑将整个value
对象的ngValue
属性绑定更改为building
。
<select class="form-control" formControlName="building" (change)="onSelect($event.target.value)">
<option *ngFor="let building of buildingList" [ngValue]="building">
{{building.buildingName}}
</option>
</select>