在angular6中为“编辑”表单预先选择的选项(“下拉”)

时间:2019-01-10 18:21:04

标签: javascript angular typescript angular6

我在我的网站中为添加类别创建了一个编辑表单。

我需要在进入编辑页面时选择要下拉的类别值。

1-我将请求发送到服务器以获取详细信息:

  public GetCatDetail(id:number){
    this.catService.GetCatDetail(id).subscribe((data)=>{
    this.cat=data,
    this.editCatFG.setValue({
      pFaName:[data.pFaName],
      pEnName:[data.pEnName],
      subCat:[data.subCat]
    }),
    this.selectedCat=data.subCat
  })
  }

2-向服务器发送请求以获取要填充的类别列表。

 public GetAllCat(){
  this.catService.GetAllCatList().subscribe((data)=>{
  this.cats=data
  })
 }

3-我在html中填写下拉列表:

    <select style="margin-right: 105px;" name="roleLevel" formControlName="subCat" [(ngModel)]="selectedCat">
                    <option  selected>    دسته اصلی </option>
                    <option *ngFor="let cat of cats" selectedCat="cat.id" [value]="cat.id" >{{cat.pFaName}}</option>
     </select>

我现在需要选择数据库中类别所存在的值,并在下拉列表中的表单中进行选择。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

当用于options列表的数组是复杂对象而不只是stringnumber时,您需要使用ngValue。 试试这个:

更新:添加compareWith以选择默认值

<select style="margin-right: 105px;" name="roleLevel" formControlName="subCat" [(ngModel)]="selectedCat" [compareWith]="compareById">
                    <option *ngFor="let cat of cats"  [ngValue]="cat" >{{cat.pFaName}}</option>
     </select>

在您的组件中:

compareById(o1, o2) {
    return o1.id === o2.id
  }

如果cat.id = 0不是来自服务,则可以将其添加到数组中,如下所示:

public GetAllCat(){
  this.catService.GetAllCatList().subscribe((data)=>{
  this.cats=data
  //adding the value for id=0;
  this.cats.push({id:0, pFaName: '    دسته اصلی '});
  })
 }
相关问题