2016-09-19 93 views
1

我面临着一个打字稿错误打字稿错误 - TS2339上ComponentRef

错误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:尽管打字稿引发这个错误,但是这段代码正如我想要的那样工作(在开发版本中)。但不能做督促建立

感谢

回答

0

你可以写:

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

或者

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

它的工作非常感谢.... – i7326