How to keep form data when switching tabs/routes?

后端 未结 1 903
清歌不尽
清歌不尽 2021-01-04 11:26

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

相关标签:
1条回答
  • 2021-01-04 12:11

    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">
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题