切换标签/路线时如何保留表格数据? [英] How to keep form data when switching tabs/routes?

查看:89
本文介绍了切换标签/路线时如何保留表格数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

切换路线时.如何保持应用程序的状态不变? 我观察到每次切换选项卡时Angular类都会重新初始化.

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.

例如 柱塞

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.`;
    }
}

推荐答案

在导航时会创建新的组件实例. 您可以通过多种选择来保持自己的价值:

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

  • 将其存储在应用程序绑定服务中
  • 将其存储在持久性存储中(localStrage/sessionStorage)

这个矮人 http://plnkr.co/edit/iEUlfrgA3mpaTKmNWRpR?p=preview实现前一个.重要的位子是

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

服务(searchService.ts)

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));

将其注入到SearchPage组件中:(并不是因为导航时会创建一个新的组件实例,所以您不应覆盖构造函数中的值)

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;
  }

}

更新输入的服务值:

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

这篇关于切换标签/路线时如何保留表格数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆