I use ng-bootstrap to create 3 tabs, each tab is a separate component inside a mutual parent component. Each child component contains several text inputs, when I switch between child components, the input text values are gone. How to preserve all the input values when switching tabs?
-
Found an ideal example in Ionic (https://codepen.io/delaman/pen/xJDhn), but still could not find a similar one in Angular – Hoàng Nguyễn Jan 11 '18 at 14:17
4 Answers
You can use the destroyOnHide
attribute of NgbTabset.
Usage:
<ngb-tabset [destroyOnHide]="false">
<ngb-tab>
<ng-template ngbTabTitle>
<div>Title 1</div>
</ng-template>
<ng-template ngbTabContent>
<!-- Component One-->
</ng-template>
</ngb-tab>
<ngb-tab>
<ng-template ngbTabTitle>
<div>Title 2</div>
</ng-template>
<ng-template ngbTabContent>
<!-- Component two-->
</ng-template>
</ngb-tab>
<ngb-tabset>

- 1,211
- 4
- 17
- 34
-
So, no need to bind or double-bind anything? You flip away and then back and all is remembered without being reset? – mohsenmadi Jan 11 '18 at 15:07
-
1And, what if you wanted to reset values as opposed to remembering them? Do you set a flag or something? – mohsenmadi Jan 11 '18 at 15:13
-
1
-
1Gotcha. Would have been nice if there was a flag to keep/purge values through. Thanks. Up+. – mohsenmadi Jan 11 '18 at 15:25
-
When I include this attribute the tabs get broken, only the initial tab panel is ever showing even though clicking on the other tabs changes the selected tab on the top – David Aug 03 '18 at 12:35
-
Will this also work with the [TabMenu](https://www.primefaces.org/primeng/#/tabmenu) component of PrimeNG? Or is there something similar that can be used instead for the TabMenu component? – PJvG Jan 21 '20 at 11:43
You can build a service to retain the values.
Something just simple like this will do:
import { Injectable } from '@angular/core';
@Injectable()
export class InputService {
lastName: string;
firstName: string;
constructor() { }
}
Just inject this service into each of the three tab components. They can then each set the values into the service and read the values from the service.

- 57,520
- 12
- 104
- 129
You need to store values somewhere, when you change Tab, DOM is refreshed so you lost you input.
Create an object to save your data and pass your object in route param to always keep it.
Or you can use localStorage to save your object and get it on the ngInit method.

- 2,620
- 1
- 10
- 22
You could either store your values in a service that you then read back in an ngOnInit()
method, or you could use localStorage
as is shown here to read back results in the ngOnInit()
method, results you saved during an ngOnDestroy()
method. A little learning about these lifecycle methods is warranted here.

- 2,277
- 1
- 23
- 34