iamP
iamP

Reputation: 317

How to keep entered form data of page1 after navigating back from page2 in Angular

I want to retain the form data entered in first page when I route to page 2 and navigate back on page1 ex: I have created two components: route1 and route2

route1.component.html

<p>route1 works!</p>
<form>
    <label>Name: </label>
    <input type="text"  [(ngModel)]="name"/>
    <button><a [routerLink] = "'/route2'">route2</a></button>
</form>

route2.component.html

<p>route2 works!</p>
<button><a [routerLink] = "'/route1'">route1</a></button>

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { Route1Component } from './routePages/route1/route1.component';
import { Route2Component } from './routePages/route2/route2.component';

const routes: Routes = [
    {path:'route1' , component : Route1Component},
    {path:'route2' , component : Route2Component}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

I enter any text in route1 page and click on route 2 button. I am now on route 2 page. I click on route1 button and get back on route1 page. I see that the value I entered in the textbox is not present.

Please help on how to retain the textbox value?

Upvotes: 0

Views: 1514

Answers (1)

Barremian
Barremian

Reputation: 31105

Components are stateless. To have persistent data, you could store the information in a service. And you could retrieve the value in the component from the service upon initialization.

shared.service.ts

import { BehaviorSubject } from 'rxjs';

@Injectable()
export class SharedService {
  public nameSource = new BehaviorSubject<string>('');
  public name$ = this.nameSource.asObservable();
  ...
}

route1.component.ts

import { SharedService } from './shared.service';

import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

export class Route1 implements OnInit, OnDestroy {
  public name: string;
  private closed$ = new Subject<any>();      // <-- use to close subscriptions

  constructor(private shared: SharedService) { }

  ngOnInit() {
    this.shared.name$.pipe(
      takeUntil(this.closed$)               // <-- close subscription when `closed$` emits
    ).subscribe(name => this.name = name);
  }

  ngOnDestroy() {
    this.closed$.next();         // <-- close impending subscriptions
  }
}

route1.component.html

<p>route1 works!</p>
<form>
  <label>Name: </label>
  <input type="text" [ngModel]="name" (ngModelChange)="shared.nameSource.next($event)"/>
  <button><a [routerLink] = "'/route2'">route2</a></button>
</form>

Upvotes: 1

Related Questions