簡體   English   中英

帶div的Angular2包裝組件模板

[英]Angular2 wrapping component template with div

我有一個跟蹤一堆子組件的父組件,我正在嘗試將每個子組件模板包裝在一起,以便可以使用* ngIf。 父組件可以有任意數量的子代。

不太確定如何更好地解釋它,但這實際上是我的觀點:

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

<ng-content></ng-content>

其中ng-content是子組件模板。 這可行,但是例如,當選擇child2時,我需要能夠做一些邏輯來隱藏child1模板。 我當時想用* ngIf包裹每個子組件模板,但我想不出一種方法來做這樣的事情

也許會對您有所幫助。

    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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM