You can set a key for each component that acts like an identifier for the data stored in localStorage. And at each component's ngOnInit, check if the identifier is same with the component's or not.
I created a stackblitz here: https://stackblitz.com/edit/angular-oryk5z
First, I created a model for items to be stored in localStorage:
export class LocalStorageItem{
last_component: string;
id: number;
row: number;
whatever: string;
static fromJSON = (jsonValue: string): LocalStorageItem => {
const newItem = new LocalStorageItem();
if(jsonValue !== null){
const parsedJSON = JSON.parse(jsonValue);
newItem.last_component = parsedJSON['last_component'];
newItem.id = parsedJSON['id'];
newItem.row = parsedJSON['row'];
newItem.whatever = parsedJSON['whatever'];
}
return newItem;
}
}
Then I created a service which is responsible for storage operations. In the initLocalStorage() method, this service takes the component's identifier as a parameter and checks if the stored item's identifier is the same. If not, it creates a new item with the identifier.
export class LocalStorageService {
readonly filterStorageKey = 'component_storage_key'
constructor() { }
initLocalStorage = (storageKey: string) => {
var storedItem = LocalStorageItem.fromJSON(localStorage.getItem(this.filterStorageKey));
if (storedItem === null || (storedItem.last_component !== storageKey)) { // if no value is stored / store is empty
const newStoreItem = new LocalStorageItem();
newStoreItem.last_component = storageKey;
this.setLocalStorage(newStoreItem);
}
storedItem = LocalStorageItem.fromJSON(localStorage.getItem(this.filterStorageKey)); // this line is for debug purposes
return storedItem;
}
getLocalStorage = () => {
return LocalStorageItem.fromJSON(localStorage.getItem(this.filterStorageKey));
}
setLocalStorage = (item: LocalStorageItem) =>{
localStorage.setItem(this.filterStorageKey, JSON.stringify(item));
}
}
And then in each component, call initLocalStorage() method of service at ngOnInit with storage identifier of that component:
export class YDashboardComponent implements OnInit, ILocalStorageManager { // This interface is to be sure that the component defines storageKey property
readonly storageKey = 'y-dashboard';
storedItemFromService;
constructor(private localStorageService: LocalStorageService) { }
ngOnInit() {
this.storedItemFromService = this.localStorageService.initLocalStorage(this.storageKey);
}
}
I hope that will give a clue about what you want to build.