[英]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
列表的數組是復雜的對象,而不僅僅是string
或number
,則需要使用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.