繁体   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