繁体   English   中英

Angular2:实现选项卡

[英]Angular2: implementing the tabs

我想在页面上实现选项卡,因此完成了本教程

https://dzone.com/articles/learning-angular-2-creating-a-tabs-component但在某种程度上它不适用于Plunker: http ://plnkr.co/edit/jwBB7jd8KDXmndGBz4ZN?p=preview

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

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


}

和选项卡组件:

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

    @Component({
      selector: 'tabs',
      template: `<ul class="nav nav-tabs">
      <li *ngFor="let tab of tabs" [hidden]='true' (click)="selectTab(tab)" [class.active]="tab.active">
        <a>{{tab.title}}</a>
      </li>
    </ul>
    <ng-content></ng-content>`,
      styleUrls: ['./tabs.component.css']
    })
    export class Tabs implements AfterContentInit{
      @ContentChildren(Tab) tabs: QueryList<Tab>;



     ngAfterContentInit() {
      let activeTabs = this.tabs.filter((tab)=>tab.active);

      if(activeTabs.length === 0) {
        this.selectTab(this.tabs.first);
      }
    }

    selectTab(tab: Tab){
      this.tabs.toArray().forEach(tab => tab.active = false);
      tab.active = true;
    }
    }

请注意:这是我第一次与Plunker合作,所以请原谅。 我希望有人可以帮助我。

谢谢。

我有一个非常简单的解决方案home.component.ts

<ul class="tabs">
<li [ngClass]=" {'active-tab': tab==1 }"><a (click)=" tab = 1 " href="javascript:void(0)">Tab 1</a></li>
<li [ngClass]=" {'active-tab': tab==2 }"><a (click)=" tab = 2 " href="javascript:void(0)">Tab 2</a></li>
<li [ngClass]=" {'active-tab': tab==3 }"><a (click)=" tab = 3 " href="javascript:void(0)">Tab 3</a></li>df
</ul>

<div class="tab-panel" id="tabPanel1" *ngIf="tab==1">
    ABC TAB 1
</div>
<div class="tab-panel" id="tabPanel2" *ngIf="tab==2">
    ABC TAB 2
</div>
<div class="tab-panel" id="tabPanel3" *ngIf="tab==3">
    ABC TAB 3
</div>

如果要在页面加载时激活任何选项卡,然后将值分配给“ tab”变量,则无需使用任何第三方组件,这非常容易

home.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  tab: number = 3;
  constructor() { }

  ngOnInit() {
  }

}

Angular未加载。 创建时,您需要将“ punker”设置为angular 2应用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM