2

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?

Hoàng Nguyễn
  • 1,121
  • 3
  • 33
  • 57

4 Answers4

6

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>
Freshchris
  • 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
  • 1
    And, 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
    I would work with the tabChange event and reset the values there. – Freshchris Jan 11 '18 at 15:22
  • 1
    Gotcha. 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
2

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.

DeborahK
  • 57,520
  • 12
  • 104
  • 129
0

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.

Léo R.
  • 2,620
  • 1
  • 10
  • 22
0

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.

mohsenmadi
  • 2,277
  • 1
  • 23
  • 34