Angular *ngIf 组件上的指令不保存值 (Ionic 3)

Angular *ngIf directive on component doesn't save value (Ionic 3)

我在 Ionic 3 上创建了 angular 个组件。 我使用 *ngIf 指令创建了几个 div 选项卡。 现在我可以使用按钮在选项卡之间切换..

但是,当我导航到包含该组件的 html 主页面的其他部分时,*ngIf 指令似乎失去了它的当前值。它默认返回到其原始选项卡。 这对我来说是个问题。我试图让 ngIf 指令选项卡停留在它们所在的位置.. 我怎样才能做到这一点?我应该将 ngIf 的值存储到本地存储吗?还有其他办法吗?

主 HTML 页面似乎存储 ngIf 指令值,只要 ngIf 未嵌套在组件中。

提前致谢,

您可以创建一个服务,其中包含一个状态变量,其中的选项卡处于活动状态

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

@Injectable()
export class TabService {


  tabState: number = 0;

  constructor() { }


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

  getTab() {
    return this.tabState;
  }
}

然后在您的组件中注入服务,并在初始化时获取选项卡

  currentValue = 0;

  constructor(private tabService: TabService ) {}

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

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

注意,不要忘记将服务作为提供者注入