0

我有一个 mat-form-field,其中包含我从 API 获取的数据下拉列表,并且我能够选择一个选项并将选择的选项成功保存到表单中。但是,当我回到该下拉菜单或重新加载时,未显示已保存的值,并且看起来该下拉列表中的值尚未被选中。

API 正在返回这样的对象列表

  [
     {
        personId: string,
        personName: string,
        personAge: int
      },
    ...
  ]

我在下拉列表中显示名称,但将 ID 保存在表单中

        <mat-form-field fxFlex.gt-sm="31%"  *ngIf="isPersonRequired()">
            <mat-label>
                Name
            </mat-label>
            <mat-select
                formControlName="personName"
                [required]="isPersonRequired()">

                <mat-option
                    *ngIf="(items | async)?.length==0"
                    disabled>

                    No item found
                </mat-option>
                <mat-option
                    *ngFor="let p of items | async"
                    [value]="p.personId">

                    {{p.personName}}
                </mat-option>
            </mat-select>
            <mat-error>
                Field Is Required
            </mat-error>
        </mat-form-field>

选择并保存名称后,当用户返回该页面和下拉菜单时,如何将其显示回来?

谢谢

4

1 回答 1

0

如果您想在重新加载或刷新时保留数据,您可以使用 localStorage 将数据保留在浏览器存储中,直到您不再需要它为止。为此,我建议您创建一个共享服务来跟踪所有用户选择,然后在完成后将其删除。这是共享服务的示例

import { Injectable } from '@angular/core';

@Injectable()
export class SharingService {
  private storageName: string = "Settings";

  constructor() { }

  setSettings(data: any) {
    localStorage.setItem(this.storageName, JSON.stringify(data));
  }

  getUserSettings() {
    let data = localStorage.getItem(this.storageName);
    return JSON.parse(data);
  }

  clearUserSettings() {
    localStorage.removeItem(this.storageName);
  }

  cleanAll() {
    localStorage.clear()
  }

}
于 2021-03-17T00:02:17.820 回答