Angular 2- what is the best way to set multiple components in one path without losing data using TypeScript -
export const routes: routes = [ {path: '', redirectto: 'login', pathmatch: 'full'}, { path: 'login',component: logincomponent }, {path: 'main', component: maincomponent ,}, { path: 'dashboard',component: dashboardcomponent, children: [ { path: ':id', children: [ { path: '',redirectto: 'registration', pathmatch: 'full'}, { path: 'registration', component: registrationcomponent, }, { path: 'contact', component: contactcomponent }, ] } ] },];
how maintain input fields data in contact , registration component. multiple child views data lost on moving 1 child component child.
dashboard component 1:
@component({ selector: 'registration', template: `<input type="text" required>`,}) export class registrationcomponent{ constructor(public router: router) {}}
dashboard component 2:
@component({ selector: 'contact', template: `<input type="text" required>`,}) export class contactcomponent{ constructor(public router: router) {}}
<div> <a class="registratin" [routerlink]="[':/registaration']" routerlinkactive="active"> </a> <a class="contact" [routerlink]="[':/contact']"> </a> </div> <div class="outer-outlet"> <router-outlet></router-outlet> </div>
when route registrationcomponent
contactcomponent
, angular destroys current component i.e. registrationcomponent
, loads new contactcomponent
. why lose input data in registration template.
there different ways tackle this:
1.use structural directives or [hidden]
routing should ideally used if components differ entirely in context. instead out routing, use ngif hide/show components. ..
<registration [hidden]="id!=1"></registration> <contact [hidden]="id!=2"></contact>
2.use service(s) communicate data
a. inject service providers , set/get data to/from service
b. use resolve guard prefetch data before navigating
if want dig deeper, go through angular 2 offical routing example implements different routing behaviours.
Comments
Post a Comment