Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
902 views
in Technique[技术] by (71.8m points)

angular - How to keep form data when switching tabs/routes?

When switching routes. How to keep state of the application as it is? I observed that Angular class is reinitialize every time I switch tabs.

For eg. Plunker

import {Component, View, CORE_DIRECTIVES} from 'angular2/angular2'
@Component({
})
@View({
  template: `
 <input class="form-control" [value]="test"> </input>
 <br>
 {{test}}
`
})
export class SearchPage{
    test = `Type something here go to inventory tab and comeback to search tab. Typed data will gone.
    I observed that Angular class is reinitialize every time I switch tabs.`;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Indeed new component instance are created when navigating. You have several options to hold your value:

  • Store it in a app-bound service
  • Store it in a persistent storage (localStrage / sessionStorage)

this plunker http://plnkr.co/edit/iEUlfrgA3mpaTKmNWRpR?p=preview implements the former one. Important bits are

the service (searchService.ts)

export class SearchService {
  searchText: string;
  constructor() {
    this.searchText = "Initial text";
  }
}

Binding it when bootstraping the app, so that the instance is available through the whole app:

bootstrap(App, [
  HTTP_BINDINGS,ROUTER_BINDINGS, SearchService,
  bind(LocationStrategy).toClass(HashLocationStrategy)
  ])
  .catch(err => console.error(err));

Injecting it in your SearchPage component: (not that you should not override the value in the constructor since a new component instance is created upon navigation)

export class SearchPage{
  searchService: SearchService;

  constructor(searchService: SearchService) {
    this.searchService = searchService;
  }

}

Updating the service value on input:

<input class="form-control" [value]="searchService.searchText"
 (input)="searchService.searchText = $event.target.value">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...