Angular(6)表单在http get

时间:2018-06-09 14:24:51

标签: angular select

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

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

以下是观点:

        <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的第一项被选中,但它应该是另一项

如果我不使用这个`[value] =“selectedSalle”,则不会选择任何内容并且选择为空白

我从以下地址获得“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"所需的选项,所以我把它放回去了。

1 个答案:

答案 0 :(得分:3)

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
}

工作DEMO