刷新后保留Angular 2选项卡

时间:2017-08-01 07:31:01

标签: angular tabs angular2-template angular2-directives

我在标签功能上工作正常,但我希望在页面刷新时保持选定的标签处于活动状态。

<tabs>
  <tab [tabTitle]="'Tab 1'">Tab 1 Content</tab>
  <tab tabTitle="Tab 2">Tab 2 Content</tab>
</tabs>

的src / tabs.ts

import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';
import { Tab } from './tab';

@Component({
  selector: 'tabs',
  template:`
    <ul class="nav nav-tabs">
      <li *ngFor="let tab of tabs" (click)="selectTab(tab)" [class.active]="tab.active">
        <a href="#">{{tab.title}}</a>
      </li>
    </ul>
    <ng-content></ng-content>
  `
})
export class Tabs implements AfterContentInit {

  @ContentChildren(Tab) tabs: QueryList<Tab>;

  // contentChildren are set
  ngAfterContentInit() {
    // get all active tabs
    let activeTabs = this.tabs.filter((tab)=>tab.active);

    // if there is no active tab set, activate the first
    if(activeTabs.length === 0) {
      this.selectTab(this.tabs.first);
    } 
  }

  selectTab(tab: Tab){
    // deactivate all tabs
    this.tabs.toArray().forEach(tab => tab.active = false);

    // activate the tab the user has clicked on.
    tab.active = true;
  }

}

的src / tab.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'tab',
  styles: [`
    .pane{
      padding: 1em;
    }
  `],
  template: `
    <div [hidden]="!active" class="pane">
      <ng-content></ng-content>
    </div>
  `
})
export class Tab {
  @Input('tabTitle') title: string;
  @Input() active = false;
}

这是一名工作人员:

http://plnkr.co/edit/ctzfDxkGDWvnetWVRfwI?p=preview

1 个答案:

答案 0 :(得分:1)

您需要的是在selectTab期间将选定的标签索引存储在存储中,并在初始化ngAfterContentInit期间进行检查。 对于此示例,我们将使用localStorage。

在src / tabs.ts

ngAfterContentInit() {
    // get all active tabs
    let activeTabs = this.tabs.filter((tab)=>tab.active);
    //get the active tab from storage,
    //if there are no stored, first tab is selected
    let selectedIndex: number =  parseInt(localStorage.getItem('selectedTabIndex'))  || 0;
    this.selectTab(this.tabs.toArray()[selectedIndex]);

}

selectTab(tab: Tab){
    // deactivate all tabs
    this.tabs.toArray().forEach(tab => tab.active = false);
    //store selected tab index in localStorage
    let selectedIndex: number = this.tabs.toArray().indexOf(tab);
    localStorage.setItem('selectedTabIndex',selectedIndex);
    // activate the tab the user has clicked on.
    tab.active = true;
}

work plunker:http://plnkr.co/edit/4ZkcBulnpqYcxjtQgXuG?p=preview