Javascript 选择Angular 7下拉列表中的第一个元素
我正在以Javascript 选择Angular 7下拉列表中的第一个元素,javascript,jquery,angular,Javascript,Jquery,Angular,我正在以地图的形式获取下拉列表的内容。当我得到地图时,它会按照键的升序进行排序。 在html中显示时,我设置了pipe keyvalue,并提供了一个函数以值的升序对项目进行排序。 现在,我正在尝试选择此下拉列表的第一个元素,但无法选择。 我尝试了jQuery方法来选择第一个元素。 我尝试将选择框的ngModel设置为地图的第一个值,但它将该值设置为地图中接收到的按键排序的第一个值。 My HTML: <select class="form-control" id="empId" [(n
地图的形式获取下拉列表的内容。当我得到地图时,它会按照键的升序进行排序。
在html中显示时,我设置了pipe keyvalue,并提供了一个函数以值的升序对项目进行排序。
现在,我正在尝试选择此下拉列表的第一个元素,但无法选择。
我尝试了jQuery方法来选择第一个元素。
我尝试将选择框的ngModel设置为地图的第一个值,但它将该值设置为地图中接收到的按键排序的第一个值。
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>
我需要的是Alex应该被预先选中。
{{emp.value}
您可以像上面那样使用选定的属性
,然后在订阅之前设置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>
我强烈建议你使用Angular的反应形式!并在接收数据时将select的值设置为所需的值。不要使用ngModel,因为它已被弃用,并且应该在Angular 7之前删除(或者很快就会删除)。检查一下,我不明白。您说希望值按升序排列,但要使用keyvalue:descOrder。我假设descOrder按降序排列字符串!?你能把它寄出去吗?
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>
this.empId = 5;
this.commonService.getEmployeeList())
.subscribe((response) => {
this.empNames = response;
});
<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;
})
);