1
import { NgModule} from '@angular/core';
export const my_custom_format{
var date_format=localStorage.getItem('date_format')
}
...

@NgModule({
  imports [
  ...
  ],
  declarations [
  ...
  ],
  entryComponents [
  ...
  ],
  providers [
  {provide: LOCALE_ID, useValue:date_format}
  ]
})

And when I come to page, my date_format gets the value from localStorage. But if my item in locaLstorage gets change, date_format is not updating. How to do that?

3 Answers3

1

Imporant - This is a hack and I don't know if it will achieve what you are trying to do. My guess is that you are trying to inject the locale id to some of your components and use them there.

If you are trying to change the language this way, then I'm sorry to tell you that it does not work by changing the locale id from your local storage.

You can try the following (and see if it works)

export class LocalStorage {
    public static get DateFormat() {
        return localStorage.getItem('date_format');
    }
}

and for the providers part:

{provide: OWL_DATE_TIME_FORMATS, useValue:LocaleStorage.DateFormat}
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
  • Dear sir, but whenever I change value in localStorage the application gets old one value from localStorage not updated one this is main problem – Yameshkumar Mahule Sep 25 '19 at 12:14
  • I really don't understand the problem. Can you explain it more thoroughly please? How do you know that the application does not get the new value. What is the syptom? – Athanasios Kataras Sep 25 '19 at 14:07
1

The way dependency injection (DI) works in angular, the only way, at least for now, is to save the value in localStorage & refresh the app/page & then pick that value in either useFactory,useValue or useClass on app load.

In a component's life cycle, there is just one runtime execution that happens for the providers. If we want to change the provider, we have to unmount & remount the component again, as far as I know.

Junaid
  • 4,682
  • 1
  • 34
  • 40
  • Could you please explain how to unmount and remount a component? – Ramin Ar Feb 14 '22 at 13:29
  • 1
    Check this SO answer, hope it helps. https://stackoverflow.com/a/52354498/4109794 If it doesn't, try refresh the angular app & pick value from localStorage etc using useValue – Junaid Feb 16 '22 at 14:17
0

In angular, providers are a singleton classes, meaning that they are initialized once and each place (component etc) that will request for it will get the same instance that was initialized.

After we understands this we can understand your case. The value of LOCAL_ID get initialized once with date_format value, from here on the value of LOCAL_ID won't get updated with changes to date_format.

One thing you can do, is to have this provider in each component that you want that will get the latest value of date_format.

benshabatnoam
  • 7,161
  • 1
  • 31
  • 52