角度 (6) 表单在 http get 之后选择中选择所选项目



我想在表单选择中选择一个选项,但我找不到方法。

我已经在网上检查了许多类似的问题,但没有找到使解决方案适应我的代码的方法。

这是视图:

<select class="form-control" #selectedValue name="selectedSalles" 
id="selectedSalles" [(ngModel)]="selectedSalle" 
(ngModelChange)="addSalleToSelected($event)">
<option *ngFor="let salle of allSalleEtb | async" 
[ngValue]="salle" [value]="selectedSalle" >
{{salle.nom}}
</option>
</select>

使用此代码,allSalleEtb选择列表的第一项,但它应该是另一项

如果我不使用此"[值]="选定Salle",则不会选择任何内容,并且选择为空

我从以下位置获得"salle"对象:

public getSlot(){
this.creneauService.getSlot(this.idEtablissement, this.idCreneau)
.subscribe((data: CourseSlot) => {
this.selectedSalle = data.salle;
}
);
}

欲了解更多信息 :

对象 "Salle" 包含 "nom" 和 "id" 属性:

salle:Object {idSalle: 2, nom: "110A"}

控制器从 httpClient get 请求接收信息:

getSlot(idEtablissement: number, idCreneau: number){
const url =  environment.API_URL + "/etablissement/" + idEtablissement + "/creneaux/" + idCreneau;
return  this.httpClient.get(environment.API_URL + "/etablissement/" + idEtablissement + "/creneaux/" + idCreneau);
}

非常感谢您的帮助(如果有的话(!

-----------编辑

当我更改"salle"的值(ngModelChange)="addSalleToSelected($event)"时,SelectedSalle被编辑,并用于发布表单:

addSalleToSelected(salle){ 
this.salle = salle;
this.selectedSalle = salle;
console.log("salle added"); 
console.log(salle);
}

有了我所有的试探,我忘记并删除了所需的选项[ngValue]="salle",所以我把它放回去了。

HTML 在选项而不是完整对象的值中分配id

<select class="form-control" #selectedValue name="selectedSalles" 
id="selectedSalles" [(ngModel)]="selectedSalle" 
(ngModelChange)="addSalleToSelected($event)">
<option *ngFor="let salle of allSalleEtb" [value]="salle.idSalle"> //==== assign id in value rather than complete object
{{salle.nom}}
</option>
</select>

TS

public getSlot(){
this.creneauService.getSlot(this.idEtablissement, this.idCreneau)
.subscribe((data: CourseSlot) => {
this.allSalleEtb = data.salle; // set all data here
this.selectedSalle = this.allSalleEtb[0].idSalle; // set first as selected
});
}

根据 ID 查找所选对象

addSalleToSelected(value){ 
this.salle = this.allSalleEtb.find(salle => salle.idSalle == value); // find selected object by finding in original data by ID
}

工作演示

最新更新