[英]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.