簡體   English   中英

在angular6中為“編輯”表單預先選擇的選項(“下拉”)

[英]pre-selected option ( Dropdown ) for Edit form in 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>

現在,我需要選擇數據庫中類別所存在的值,並在下拉列表中的表單中進行選擇。

我怎樣才能做到這一點 ?

如果用於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: '    دسته اصلی '});
  })
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM