简体   繁体   English

离开页面时使用 sessionStorage 保留 select 值中的值 Angular

[英]Using sessionStorage to keep values in select values when leaving the page Angular

Well, the title almost says it all,好吧,标题几乎说明了一切,

I'm using sessionStorage of angular to store some values selected in a form and show them again as selected values when the user gets back to that form, The issue that I'm facing is that I can store the values and recuperate them but I can't get them selected in my select inputs我正在使用 angular 的 sessionStorage 来存储在表单中选择的一些值,并在用户返回该表单时再次将它们显示为选定值,我面临的问题是我可以存储这些值并恢复它们,但我无法在我的 select 输入中选择它们

I've tried to use [selected] but it still doesn't show up !我尝试使用 [selected] 但它仍然没有出现! please help请帮忙

Thank you谢谢

That's because you need to know with wich type of data are you handling in the select and how to correctly map that data, i understand your problem because it's normal at the beginning to have them so here some tips from me, that show how to handle this situation, all code are commented, if you don't understand something feel free to ask for more information.那是因为您需要知道您在 select 中处理的数据类型以及如何正确处理 map 数据,我理解您的问题,因为一开始就有这些数据是正常的,所以这里有一些我的提示,说明如何处理在这种情况下,所有代码都已注释,如果您有不明白的地方,请随时询问更多信息。

Stackblitz: https://stackblitz.com/edit/angular-qfncmm Stackblitz: https://stackblitz.com/edit/angular-qfncmm

HTML: HTML:

<p>Select with only string</p>


<select  [(ngModel)]="selectedValue">
<!--  You cant bind in value an object you need to bind string ids-->
  <option [value]="x.name" *ngFor="let x of selectData">{{x.name}}</option>
</select>

<p>You just selected to be</p><strong>{{selectedValue}}</strong>


<p>Save data in localstorage</p>
<button type="button" (click)="saveData()">SAVE IT</button>
<button type="button" (click)="fetchData()">FETCH IT</button>

<hr>

<p>Select with object data</p>


<select  [(ngModel)]="selectedObject">
  <!--  You can bind object with ngValue-->
  <option [ngValue]="x" *ngFor="let x of selectData">{{x.name}}</option>
</select>

<p>You just selected to be</p> <strong>{{selectedObject?.id}} - {{selectedObject?.name}}</strong>


<p>Save data in localstorage</p>
<button type="button" (click)="saveDataObject()">SAVE IT</button>
<button type="button" (click)="fetchDataObject()">FETCH IT</button>

TS: TS:

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

// tslint:disable-next-line:class-name
interface DataI {
  id: number;
  name: string;
}

const data: DataI[] = [
  {id: 1, name: 'Markus'},
  {id: 2, name: 'Anna'},
  {id: 3, name: 'Jhon'},
  {id: 4, name: 'Lori'},
];

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  selectData: DataI[];
  selectedValue: string;
  selectedObject: DataI;

  constructor() {
    this.selectData = data;
  }


  // In case you want to store object, the local and session storage don't accept objects, so you need to stringify them
  saveDataObject() {
    localStorage.setItem('selectedObj', JSON.stringify(this.selectedObject));
    // Refresh the page only for the example of rivisiting the app
    location.reload();
  }

  // When you fetch them just parse the string in json
  fetchDataObject() {
    this.selectedObject = JSON.parse(localStorage.getItem('selectedObj'));
    this.mapSelectedData();
  }

  /* When you fetch the object the data will not be displayed on the select because in javascript you can't
  assume that a obj equal to another obj only because they share same data so you need the original reference used
   */

  mapSelectedData() {
    this.selectedObject = this.selectData
      .filter(x => x.id === this.selectedObject.id)
      .map(x => x)
      .reduce(x => x);
  }


  saveData() {
    localStorage.setItem('selected', this.selectedValue);
    // Refresh the page only for the example of rivisiting the app
    location.reload();
  }

  fetchData() {
    this.selectedValue = localStorage.getItem('selected');
  }
}

I stored everything in localstorage, bacause session storage once you leave the domain, the session expire and delete all data if you want to save it persistently you need to store in localstorage, if you want to save only for the session, using sessionStorage is good with some redux pattern, but for saving some data just use a service that store all the data in memory. I stored everything in localstorage, bacause session storage once you leave the domain, the session expire and delete all data if you want to save it persistently you need to store in localstorage, if you want to save only for the session, using sessionStorage is good使用一些 redux 模式,但为了保存一些数据,只需使用将所有数据存储在 memory 中的服务。

Angular Material Select by default, compares selected objects by reference. Angular 材质 Select 默认情况下,通过引用比较选定对象

Stackblitz Demo Stackblitz 演示

Explanation:解释:

when working with primitive values like string or numbers, you don't have to worry about it, but when you work with objects , you want to pass in a custom comparer to your select.使用原始值(如字符串或数字)时,您不必担心,但使用对象时,您希望将自定义比较器传递给 select。

<mat-select multiple [(ngModel)]="selectedObjects" [compareWith]="comparer">

your comparer should be simple function that compares two objects by a prop of your choice:您的比较器应该是简单的 function 通过您选择的道具比较两个对象:

interface obj {
  name: string,
  value: number
}

comparer(o1: obj, o2: obj): boolean {
    return o1.name === o2.name;
}

then, we can set values as we wanted:然后,我们可以根据需要设置值:

Component:零件:

 // all objects
allObjects : obj[] = [
  {name: 'AAA', value: 1},
  {name: 'BBB', value: 2},
  {name: 'CCC', value: 3}
];

// selected object
selectedObjects : obj[];

ngOnInit() {
  // define default selection - notice we dont care about the value (99).
  // even though the value 99 does not appear in the options list,
  // due to our comparer we only compare by NAME for the item to be selected.

  this.selectedObjects = [{name: 'AAA', value: 99}, {name: 'CCC', value: 99}];    
}

HTML: HTML:

<mat-form-field>
  <mat-select multiple [(ngModel)]="selectedObjects" [compareWith]="comparer">
    <mat-option *ngFor="let iobject of allObjects" [value]="iobject">{{iobject.name}}</mat-option>
  </mat-select>
</mat-form-field>

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

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