2017-02-24 75 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

你是對的,我必須投它,謝謝 –