0
votes

I have a mat-form-field that has a dropdown of data that i fetch from an API and I am able to select an option and save the picked option to the form successfully. However as I come back to that dropdown or reload, the saved value is not being shown and it looks like the value in that dropdown hasn't been selected.

The API is returning a list of objects like this

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

Im displaying the Name in the dropdown but saving the ID in the form

        <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>

Once a name has been selected and saved, how can i display it back when a user comes back to that page and dropdown?

Thanks

1

1 Answers

0
votes

If you want to keep the data on reload or refresh you can use localStorage to keep the data in browser storage until you don't need it anymore. To accomplish this I would recommend you to create a Shared Service to keep track of all the user selection then remove it when done. Here is an example of Shared Service

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

}