0
votes

I created angular components on Ionic 3. and I created several div tabs using *ngIf directive. Now I can switch between tabs using buttons..

However, when I navigate to other section of main html page which is containing that component, *ngIf directive seems to lose its current value. It defaults back to its original tab. This is a problem for me. I'm trying to make ngIf directive tab stay at where they are.. How can I accomplish this? should I store ngIf's value to local storage? is there any other way?

Main HTML page seems to store ngIf directive value as long as ngIf is not nested within a component.

Thanks in advance,

1
No solutions found yet... please help! - jamesharvey

1 Answers

2
votes

You can create a service that holds a state variable of which tab is active

import { Injectable } from '@angular/core';

@Injectable()
export class TabService {


  tabState: number = 0;

  constructor() { }


  setTab(index: number) {
    this.tabState = index;
  }

  getTab() {
    return this.tabState;
  }
}

Then in your component, inject service, and on init, get tab

  currentValue = 0;

  constructor(private tabService: TabService ) {}

  ngOnInit() {
    this.currentValue = this.tabService.getTab();
  }

  currentValueChange(currentValue){
    this.currentValue = currentValue;
    this.tabService.currentValueChange(currentValue);
  }

Note, don't forget to inject service as a provider