无法使用 ngmodel 使选择正常工作



我有一个"查找"选择,需要作为"被动"控件工作:突出显示所选选项并作为"主动"控件:让用户选择选项并启动一些操作(加载相应实体的详细信息(。我尝试了很多,但无法使其正常工作:

<select
class="browser-default custom-select"
(ngModelChange)="onEdit($event)" [(ngModel)]="selected.id" [ngModelOptions]="{standalone: true}">
<option [ngValue]="null">{{ '::Licences:SelectLicence' | abpLocalization }}</option>
<ng-container *ngIf="licencesLookupData$ | async">
<option
*ngFor="let l of licencesLookupData$ | async"
[ngValue]="l.id"
[selected]="l.id === selected.id"
>
{{ l.id }} &nbsp;&nbsp; {{ l.displayName | defaultValue }}
</option>
</ng-container>
</select>

起初,我试图避免使用 ngModel,但后来我遇到了 id 的问题 - 它是一个整数,但被视为字符串。现在类型是正确的(数字(,但永远不会选择所选选项,即使加载了正确的数据并且 selected.id 获得了数字值也是如此。

查找是带有数字 id 键的普通可观察对象:

licencesLookupData$: Observable<Common.Lookup<number>[]>;
export interface Lookup<T> {
id: T;
displayName: string;
}

在编辑方法上:

onEdit(id?: number) {
if (id === null) {
this.onAdd();
return;
}
this.licencesLoading = true;
this.licencesService
.getById(id)
.pipe(finalize(() => (this.licencesLoading = false)), takeUntil(this.destroy))
.subscribe((state: Licences.LicenceWithFlatProperties) => {
this.selected = state;
this.buildForm();
this.get();
});
}

经过多次试验,最终对我有用:

<select
class="browser-default custom-select"
(change)="onEdit($event.target.value)"
>
<option [value]="">{{
'::Licences:SelectLicence' | abpLocalization
}}</option>
<ng-container *ngIf="licencesLookupData$ | async">
<option
*ngFor="let l of licencesLookupData$ | async"
[ngValue]="l.id"
[value]="l.id"
[selected]="l.id == selected.id"
>
{{ l.id }} &nbsp;&nbsp; {{ l.displayName | defaultValue }}
</option>
</ng-container>
</select>
onEdit(idString: string) {
const id = Number(idString);
if (isNaN(id)) {
this.onAdd();
return;
}
this.licencesLoading = true;
this.licencesService
.getById(id)
.pipe(finalize(() => (this.licencesLoading = false)), takeUntil(this.destroy))
.subscribe((state: Licences.LicenceWithFlatProperties) => {
this.selected = state;
this.buildForm();
this.get();
});
}

最新更新