我一直在尝试制作一个选项卡视图,并认为内容投影可能是一个好方法。我从这篇文章中学到了它。我认为我可以通过输入给定的组件数组来使其动态化,并且它们将显示为所选选项卡的页面。
这是我这样做的尝试:
@Component({
selector: 'my-app',
template:`
<h1>Experiments</h1>
<button class="add-button" (click)="add()">Add</button>`
})
export class App {
components:Array<any> = [PrepSetupTab,FinalizeTab]
constructor(private cdr: ChangeDetectorRef,
private compFR: ComponentFactoryResolver,
private viewContainer: ViewContainerRef ){}
add():void{
var transTabRefs: Array<any>= []
this.components.forEach(tabComponent=>{
let compFactory = this.compFR.resolveComponentFactory(tabComponent);
let compRef = this.viewContainer.createComponent(compFactory);
let tabFactory = this.compFR.resolveComponentFactory(Tab);
let transcludedTabRef = this.viewContainer.createComponent(tabFactory,this.viewContainer.length - 1, undefined, [[compRef.location.nativeElement]]);
transTabRefs.push(transcludedTabRef.location.nativeElement);
})
let tabsFactory = this.compFR.resolveComponentFactory(Tabs); // notice this is the tabs not tab
this.viewContainer.createComponent(tabsFactory,0,undefined,[transTabRefs]);
}
}
旁注, add() 作为按钮的单击处理程序不是为了避免此错误而使用的其他功能:"EXCEPTION: Expression has changed after it was checked"
. 如果我把它放在任何生命周期钩子中,我就会得到这个错误。虽然这是一个以后要处理的挑战。
所以基本上我在数组中创建每个组件,然后我将它们作为每个创建的选项卡组件的 ng-content 粘贴。然后取出每个 Tab 组件并将其粘贴到 Tabs 组件的 ng-content 中。
问题是选项卡组件永远不会找到动态创建的选项卡子项的 contentChildren。这是未定义内容子项的选项卡组件的代码。
@Component({
selector: 'tabs',
template:`
<ul class="nav nav-tabs">
<li *ngFor="let tab of tabs" (click)="selectTab(tab)" [class.active]="tab.active">
<a>{{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;
}
}
我似乎很清楚,选项卡组件是在不同的时间创建的,而不是当我需要从选项卡组件作为内容子项访问它们时。我也尝试过使用 ChangeDetectionRef.changeDetect() 但这没有帮助。
也许通过内容投影来完成这一切并不是最简单或最好的方法,所以我愿意接受建议。这是plunk,谢谢!