2017-02-24 70 views
2

这里是我的代码不能在动态创建的组件访问成员属性

模板:

<button (click)='openModal()'>open</button> 

.TS

@Component({ 
    ..., 
    entryComponents: [ModalComponent] 
}) 

... 

    constructor(
    ... 
    private resolver: ComponentFactoryResolver, 
    private viewContainerRef:ViewContainerRef 
) { } 


    openModal(){ 
    this.cmpRef = this.viewContainerRef.createComponent(
     this.resolver.resolveComponentFactory(ModalComponent) 
    ); 
    this.cmpRef.instance.close.subscribe(e => console.log(e)); 
    } 

我得到:

Property 'close' does not exist on type 'Component'.) 

但当我做console.log(this.cmpRef.instance);我可以看到我的组件与所有成员(包括接近)

接近是EventEmitter EN ModalComponent:

@Output() close: EventEmitter<any> = new EventEmitter<any>(); 
+0

请添加,显示了'close'函数的代码。 –

+0

@GünterZöchbauer编辑我的问题 –

回答

2

好像你的错误信息是静态的错误,而不是运行时错误。

(this.cmpRef.instance as ModalComponent).close.subscribe(e => console.log(e)); 
+1

效果很好,谢谢 –

+0

是否可以将“作为ModalComponent”放入变量中? –

+1

@BenjaminMcFerren我不这么认为,但我不是TS专家。你可以把它放在一个函数中,并将这个函数分配给一个变量。 –

1

你应该投你的实例ModelComponent为打字稿编译器把它捡起来:

(<ModalComponent>this.cmpRef.instance).close.subscribe(e => console.log(e)); 
+0

你是对的,我必须投它,谢谢 –