Let's say using I have a directive that can load components dynamically in it's viewContianerRef :
@Directive( { selector : '[loader-ref]' } )
export class LoaderDirective {
constructor ( private cd : ChangeDetectorRef ,
private viewContainer : ViewContainerRef ,
private componentResolver : ComponentResolver ) {
}
getIndexOf(viewRef:ViewRef){
return this.viewContainer.indexOf(viewRef);
}
createComponent ( dialogComponent : { new() : any } ) : Promise<ComponentRef<any>> {
return this.componentResolver
.resolveComponent( dialogComponent )
.then( ( componentFactory : ComponentFactory<any> ) => {
return this.viewContainer.createComponent( componentFactory );
} );
}
}
My component that should be loaded dynamically :
@Component({
selector:'my-dynamic-component'
})
export class myDynamicComponent{
// Is there any way to get this component's ViewRef , or HostView?
}
And I'm using LoaderDirective to load a component dynamically like this :
My App :
@Component( {
selector : 'example' ,
template:` <button (click)='getIndex()'></button> <div loader-ref></div>`
})
export class ExampleComponent {
@ViewChild( LoaderDirective ) loaderDirective : LoaderDirective;
ngOnInit(){
let waitForChunk = require( 'myDynamicComponent.ts' );
waitForChunk( ( file ) => {
this.loaderDirective
.createComponent( file[ 'default' ] )
.then( ( componentRef : ComponentRef<any> ) => {
componentRef.changeDetectorRef.detectChanges();
} );
} );
}
getIndex(){
// Here I want to get index of myDynamicComponent which is loaded
////What do I need to do ? ??
let index = this.loaderDirective.getIndexOf(what to pass ? )
console.log('My index is : '+index);
}
}
This is working , but know my question :
Inside my directive , I have a viewContainerRef , which has a method called indexOf
.
This method is supposed to return the index of the loaded component inside the viewContainerRef , but I don't know how it works and how to use it :