gpt4 book ai didi

javascript - Angular2 react 形式下拉

转载 作者:行者123 更新时间:2023-11-29 17:49:49 25 4
gpt4 key购买 nike

我刚刚学习 angular 2,并且有一个案例,我正在创建一个将成为一件设备的表单。与设备关联的字段之一是建筑物。当用户正在编辑或添加新设备时,我希望向他们显示一个下拉列表,其中包含他们可以将设备分配给的建筑物列表。 equipment-detail组件如下:

  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)
}
}

设备详情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 的原因。您应该考虑将整个 building 对象的 value 属性绑定(bind)更改为 ngValue

<select class="form-control" formControlName="building" (change)="onSelect($event.target.value)">
<option *ngFor="let building of buildingList" [ngValue]="building">
{{building.buildingName}}
</option>
</select>

关于javascript - Angular2 react 形式下拉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45089783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com