Hoàng Nguyễn
Hoàng Nguyễn

Reputation: 1170

Angular 4+ Preserve input values when switching tabs

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?

Upvotes: 2

Views: 5066

Answers (4)

Freshchris
Freshchris

Reputation: 1251

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>

Upvotes: 6

mohsenmadi
mohsenmadi

Reputation: 2377

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.

Upvotes: 0

DeborahK
DeborahK

Reputation: 60596

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.

Upvotes: 2

L&#233;o R.
L&#233;o R.

Reputation: 2708

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.

Upvotes: 0

Related Questions