繁体   English   中英

如何在垫选择下拉列表中填充现有值?

[英]How do I populate existing value in a mat-select dropdown?

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

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>

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

谢谢

如果您想在重新加载或刷新时保留数据,您可以使用 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()
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM