打字稿错误 - ComponentRef

时间:2016-09-19 19:15:05

标签: angular typescript

我正面临打字稿错误

  

错误TS2339:类型“{}”

上不存在属性“关闭”

我面临问题的代码: -

home.directive.ts

    import { Directive, ComponentFactoryResolver, ComponentRef, ViewContainerRef } from '@angular/core'; 
@Directive({
  selector: '[child]'
})
export class HomeDirective {
  constructor(private viewContainer: ViewContainerRef,
    private componentFactoryResolver: ComponentFactoryResolver) {
  }
  openComp(component:any) : ComponentRef<any> {
    this.viewContainer.clear();
    let componentFactory =
      this.componentFactoryResolver.resolveComponentFactory(component);
    let componentRef = this.viewContainer.createComponent(componentFactory);
    componentRef.instance.close.subscribe(() => {
            //do something
            });

    return componentRef;
  }

}

child.component.ts

import {  Component, EventEmitter } from '@angular/core';
import { HomeService } from '../home.service';
@Component({
  selector: 'child-component',
  providers: [HomeService],
  template: `<h3>child-component</h3>`
})
export class ChildComponent {
  close = new EventEmitter();
  constructor() {
  }
  ngOnDestroy() {
    this.close.emit('closed');
  }
}

我正在调用openComp()

home.component.ts

import {  Component ,ViewChild } from '@angular/core';
import { HomeService } from './home.service';
import { HomeDirective } from './home.directive';
import { ChildComponent } from './child/index';
@Component({
  moduleId: module.id,
  selector: 'sd-home',
  providers: [HomeService],
  templateUrl: 'home.component.html',
  styleUrls: ['home.component.css'],
  entryComponents: [ChildComponent],
})
export class HomeComponent {
  @ViewChild(HomeDirective) homeDirective: HomeDirective;
  constructor(private _homeService: HomeService) {
  }
  openChild() {
    this.homeDirective.openComp(ChildComponent);
  }
}

任何人都可以帮助我吗?我是角2和打字稿的新手。我的编纂可能是错的。如果我的编码错了,请纠正我。

PS:尽管打字稿会抛出此错误,但此代码可以正常工作(在开发版本中)。但不能做生产

谢谢

1 个答案:

答案 0 :(得分:3)

你可以写:

(<ChildComponent>componentRef.instance).close.subscribe

(<any>componentRef.instance).close.subscribe