prevent destroying component state on routing, without using RouteReuseStrategy

Viewed 1413

I researched about this topic and found that RouterReuseStrategy is a solution but i cant use RouterReuse How do i prevent destroying component state without using the RouterReuse Solution

Please consider upvoting becoz it will help get the answers.

// app.module.ts

const appRoutes: Routes = [
  { path: 'registration', component: RegistrationComponent },
  { path: 'users', component: ListComponent },
  { path: '', component: HomeComponent },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    Capitalize,
    FilterPipe,
    ListComponent,
    RegistrationComponent,
    PageNotFoundComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    FormsModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

// app.component.html

<section class="container">
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <div>    
        <a class="navbar-brand" routerLink="/">Brand</a>
      </div>  
      <!-- Collect the nav links, forms, and other content for toggling -->
      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
          <li><a routerLink="/">Home</a></li>
          <li><a routerLink="/registration">Registration</a></li>
          <li><a routerLink="/users">Users</a></li>                    
        </ul>        
      </div>
    </div>
  </nav>
</section>
<router-outlet></router-outlet>

stackblitzLink

2 Answers

You can store the state in a service that is provided on a level that is not recreated on routing, for example in AppModule or AppComponent.

Also if only the navigation only changes route params, but stays on the same route, components are not recreated and therefore you won't lose the state. But that works only for specific use cases.

Preserving route component state is one of several problems that RouteReuseStrategy is supposed to solve.

The alternative is to keep state outside of component instance, i.e. in separate provider. A developer can control which injector this provider will belong to and thus when provider instance will be destroyed.

@Component(
  ...
  template: `{{ state.bar }}`
)
class FooComponent {
  constructor(public state: FooState) {}
}

If state provider was defined in parent component, it will be destroyed when parent component is destroyed. If it was defined as module provider, it won't be destroyed at all.

Of course, if there are several FooComponent instances, they will share the state. If this isn't desirable behaviour then again, RouteReuseStrategy should be used instead.

Also, state management libraries like ngrx allow to manage states more efficiently.

Related