假设使用我有一个指令,可以在它的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 );
} );
}
}我应该动态加载的组件:
@Component({
selector:'my-dynamic-component'
})
export class myDynamicComponent{
// Is there any way to get this component's ViewRef , or HostView?
}我使用LoaderDirective动态加载一个组件,如下所示:
我的应用:
@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);
}
}这是有效的,但请记住我的问题:
在我的指令中,我有一个viewContainerRef,它有一个名为indexOf的方法。
此方法应该返回viewContainerRef中已加载组件的索引,但我不知道它是如何工作的以及如何使用它:
发布于 2016-09-18 14:18:09
我想您正在寻找ComponentRef的hostView属性
loadedView: ViewRef;
...
this.loaderDirective
.createComponent(myDynamicComponent)
.then((componentRef: ComponentRef<any>) => {
componentRef.changeDetectorRef.detectChanges();
this.loadedView = componentRef.hostView; <== this line
});
...
getIndex(){
let index = this.loaderDirective.getIndexOf(this.loadedView);
console.log('My index is : '+index);
}但在您的情况下,它将始终等于0,因为您正在触发:
this.viewContainer.clear();另请参阅angular2 2.0.0的
Update1
如果您希望访问myDynamicComponent指令中的视图,则可以利用以下内容:
@Component({
selector: 'my-dynamic-component'
})
export class myDynamicComponent {
public view: ViewRef;
}
...
this.loaderDirective
.createComponent(myDynamicComponent)
.then((componentRef: ComponentRef<any>) => {
componentRef.changeDetectorRef.detectChanges();
componentRef.instance.view = componentRef.hostView; <== add this line
});我更新了
Update2
您也可以通过以下方式获取viewRef:
constructor(private injector: Injector) {}
...
var viewRef = this.injector._view.ref;但在本例中,您将使用Injector的私有属性。这是一种糟糕的做法。
https://stackoverflow.com/questions/39552953
复制相似问题