无法访问动态创建的组件的成员属性

时间:2017-02-24 10:08:39

标签: angular

这是我的代码

模板:

<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);时,我可以看到我的组件包含所有成员(包括关闭)

close是一个EventEmitter和ModalComponent:

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

2 个答案:

答案 0 :(得分:2)

似乎您的错误消息是静态错误,而不是运行时错误。

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

答案 1 :(得分:1)

您应该将实例强制转换为ModelComponent,以便TypeScript编译器将其选取:

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