2016-04-08 81 views
0

我有一个父组件模块,用于跟踪一堆子组件,我试图让每个子组件模板都包含一个不同的元素,以便我可以使用* ngIf。父组件可以有任意数量的子组件。Angular2使用div打包组件模板

不是真的知道如何更好地解释它,但实际上,这就是我有一个观点:

<parent> 
    <child1></child1> 
    <child2></child2> 
</parent> 

<ng-content></ng-content> 

,其中n内容是子组件的模板。这可行,但我需要能够做一些逻辑来隐藏child1模板,例如,当选择child2时。我正在考虑用* ngIf来包装每个子组件模板,但是我无法想出办法做这样的事情。

+0

不理解你的问题,但是你可以使用'template'标签来使用'* ngIf' –

回答

1

也许这对你有帮助。

import { Component, ContentChildren, QueryList, AfterContentInit } from 'angular2/core'; 
    import { TabComponent } from './tab.component'; 

    @Component({ 
     selector: 'tabs', 
     template:` 
     <ul class="tab-container"> 
      <li class="tab" *ngFor="#tab of tabs" (click)="selectTab(tab)" [class.active]="tab.active"> 
      <span>{{tab.tabTitle}}</span> 
      </li> 
     </ul> 
     <div class="tab-content"> 
      <ng-content></ng-content> 
     </div> 

     ` 
    }) 
    export class TabsComponent implements AfterContentInit { 

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

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

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

     selectTab(selectedTab: TabComponent) { 
      this.tabs.toArray().forEach(tab => tab.active = false); 

      selectedTab.active = true; 
     } 

    } 

import { Component, Input } from 'angular2/core'; 

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