我有一个父组件来跟踪一堆子组件,我试图用不同的模板包装每个子组件模板,以便我可以使用 *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;
}
关于javascript - Angular2 用 div 包装组件模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36507589/