Angular 9,10-在Dropdown中的选项中设置选定项



如何将属性设置为"选择";在HTML选项中,如果来自"*"的值ngFor";循环是"循环";真";(取自组件ts文件中的response.body(

下拉代码:

<select [(ngModel)]="customer.id">
<option *ngFor="let location of locations" [ngValue]="location.id"
[selected]="location.isDefaultLocation === true? 'selected': ''">
{{location.name}}
</option>
</select>

也尝试过:

<option *ngFor="let location of locations" [ngValue] ="location.id"
[selected] ="location.isDefaultLocation === true">
{{location.name}}
</option>

也尝试过[compareWith]:

<select [compareWith]="locationFn" [(ngModel)]="customer.id">
<option *ngFor="let location of locations" [ngValue]="location.id">
{{location.name}}
</option>
</select>

在组件ts文件中:

locationFn(item1: any, item2: any): boolean {
return item1.isDefaultLocation === true;
}

它不起作用,但总是返回第一个值!!

组件内文件

selectedLocationId:number = 4; // use default value here which you want to show selected

HTML文件

<select [(ngModel)]="selectedLocationId">
<option *ngFor="let location of locations" [value]="location.id">
{{location.name}}
</option>
</select>

最新更新