You could either use a Service
or localStorage/Session Storage
for Persisting Data.
localStorage
and sessionStorage
accomplish the exact same thing and have the same API, but with sessionStorage
the data is persisted only until the window or tab is closed, while with localStorage
the data is persisted until the user manually clears the browser cache or until your web app clears the data.
I would suggest you to go for @ngx-pwa/local-storage Async local storage for Angular
For Angular 5:
npm install @ngx-pwa/local-storage@5
Register it in your RootModule
import { LocalStorageModule } from '@ngx-pwa/local-storage';
@NgModule({
imports: [
BrowserModule,
LocalStorageModule,
...
]
Inject and use it
import { LocalStorage } from '@ngx-pwa/local-storage';
@Injectable()
export class YourService {
constructor(protected localStorage: LocalStorage) {}
}
Usage
let user: User = { firstName: 'Henri', lastName: 'Bergson' };
this.localStorage.setItem('user', user).subscribe(() => {});
After you navigate back and forth just set/patch the values using one of these methods setValue()
and patchValue()
both sets the value in form control
of FormGroup
.
Service
Create a Service and Register the it in an Angular module rather than a component.
If you want an instance of a dependency to be shared globally and share state
across the application configure it on the NgModule.
You could either use Subject
or BehaviorSubject
to accomplish it.
-
Using BehaviorSubject
solved Persist class property Angular 5