0

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

            <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 获得了一个数字值,也永远不会选择选定的选项。

Lookup 是一个带有数字 id 键的普通 observable:

  licencesLookupData$: Observable<Common.Lookup<number>[]>;

  export interface Lookup<T> {
      id: T;
      displayName: string;
  }

onEdit 方法:

  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();
      });
  }
4

1 回答 1

0

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

  <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();
      });
  }
于 2020-06-25T00:12:55.207 回答