簡體   English   中英

在 Angular 7 的下拉列表中選擇第一個元素

[英]Select first element in dropdown in Angular 7

我將下拉列表的內容作為Map<number, string> 當我得到地圖時,它是根據鍵按升序排序的。 在 html 中顯示它時,我設置了管道鍵值並提供了一個函數來按值的升序對項目進行排序。
現在,我試圖選擇此下拉列表的第一個元素,但無法這樣做。
我嘗試過 jQuery 方法來選擇第一個元素。
我試圖將選擇框的 ngModel 設置為地圖的第一個值,但它將該值設置為 Map 中按鍵排序的第一個值。

My HTML:
<select class="form-control" id="empId" [(ngModel)]="empId" [disabled]="!isEditable">
    <option *ngFor="let emp of empNames | keyvalue:descOrder" [value]="emp.key">{{ emp.value }}</option>
</select>


 My ts file:

    this.commonService.getEmployeeList())
          .subscribe((response) => {
              this.empNames = response;
              this.empId = this.empNames.keys().next().value;
    });


data I am sending from server is:
{id:1,name: "Tim"},
{id:6,name: "Martha"},
{id:5,name: "Alex"},
{id:8,name: "Stacy"}


data I am receiving on screen is like:
Alex
Martha
Stacy
Tim

with Tim pre-selected

我需要的是亞歷克斯應該被預先選擇。

工作演示

<option *ngFor="let emp of empNames | keyvalue:descOrder" [value]="emp.key" [selected]="emp.id === 1">{{ emp.value }}</option>

你可以像上面一樣使用 selected attribute

然后在訂閱之前設置empId。

 this.empId = 5;

this.commonService.getEmployeeList())
      .subscribe((response) => {
          this.empNames = response;
     });

當然,您可能需要基於某種順序的另一種邏輯。 您永遠無法確定將如何接收數據。

在這種情況下,您需要從您的 api 發送訂單並按訂單過濾。

預先選擇選項的最佳方法是使用ngModel作為您的嘗試。 您的列表按鍵排序,因此您想要的不是選擇第一個項目,是的,它是第一個,但按其他順序排列,因此或者您更改代碼中的順序,或者您搜索要選擇的項目並將其存儲以進行設置模型。

我建議進行一些更改,以改進代碼並解決您的問題。

<select class="form-control" id="empId" [(ngModel)]="currentEmployer" [disabled]="!isEditable">
    <option *ngFor="let emp of employers$ | async" [value]="emp">{{ emp.value }}</option>
</select>

並使用您喜歡的功能在管道中訂購您的列表。

public currentEmployer: Employer = null;

private sortByNameAscending(e1, e2) {
    return e1.name > e2.name ? 1 : 0;
}

this.employers$ = this.commonService.getEmployeeList().pipe(
    switchMap(employers => {
        const sortedList = employers.sort(this.sortByNameAscending);
        if (sortedList.length > 0) {
            this.currentEmployer = sortedList[0];
        }
        return sortedList;
    })
);

我強烈建議您使用 Angular 的響應式表單! 並在收到數據時將選擇的值設置為您想要的值。 不要使用 ngModel,因為它已被棄用並且應該已被 Angular 7 刪除(或將很快刪除)。 檢查 這個

暫無
暫無

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

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