2016-10-30 18:57:26 +03:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
import {
|
|
|
|
Injectable,
|
|
|
|
ComponentFactory,
|
|
|
|
ComponentRef,
|
2017-03-15 18:51:46 +03:00
|
|
|
ViewContainerRef
|
2016-10-30 18:57:26 +03:00
|
|
|
} from '@angular/core';
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class ContentProjector {
|
|
|
|
instantiateAndProject<T>(componentFactory: ComponentFactory<T>,
|
|
|
|
parentView:ViewContainerRef, projectedNodesOrComponents: any[]):ComponentRef<T> {
|
|
|
|
let contextInjector = parentView.parentInjector;
|
|
|
|
|
|
|
|
let projectedNodes = [];
|
|
|
|
let componentRefs:ComponentRef<any>[] = [];
|
|
|
|
|
|
|
|
for (let i=0; i < projectedNodesOrComponents.length; i++) {
|
|
|
|
let nodeOrCompRef = projectedNodesOrComponents[i];
|
|
|
|
if (nodeOrCompRef instanceof ComponentRef) {
|
|
|
|
projectedNodes.push(nodeOrCompRef.location.nativeElement);
|
|
|
|
componentRefs.push(nodeOrCompRef);
|
|
|
|
} else {
|
|
|
|
projectedNodes.push(nodeOrCompRef);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let parentCompRef = parentView.createComponent(componentFactory, null, contextInjector, [projectedNodes]);
|
2016-11-02 01:19:37 +03:00
|
|
|
|
2017-03-15 18:51:46 +03:00
|
|
|
// using private property to get view instance
|
2017-03-15 18:50:10 +03:00
|
|
|
let viewContainer = (<any>parentView)._view;
|
|
|
|
let viewData = (<any>parentView)._data;
|
2017-03-29 10:55:46 +03:00
|
|
|
viewData.viewContainer._embeddedViews = viewData.viewContainer.embeddedViews || [];
|
2016-10-30 18:57:26 +03:00
|
|
|
for (let i=0; i < componentRefs.length; i++) {
|
|
|
|
let compRef = componentRefs[i];
|
2017-03-15 18:51:46 +03:00
|
|
|
// attach view to containter change detector
|
2017-03-29 10:55:46 +03:00
|
|
|
viewData.viewContainer._embeddedViews.push((<any>compRef.hostView)._view);
|
2017-03-15 18:50:10 +03:00
|
|
|
(<any>compRef.hostView).attachToViewContainerRef(viewContainer);
|
2016-10-30 18:57:26 +03:00
|
|
|
}
|
|
|
|
return parentCompRef;
|
|
|
|
}
|
|
|
|
}
|