Angular 类型脚本错误-ComponentRef上的TS2339
我面临打字错误 错误TS2339:类型{}上不存在属性“close” 我面临问题的代码:- home.directive.tsAngular 类型脚本错误-ComponentRef上的TS2339,angular,typescript,Angular,Typescript,我面临打字错误 错误TS2339:类型{}上不存在属性“close” 我面临问题的代码:- home.directive.ts import { Directive, ComponentFactoryResolver, ComponentRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[child]' }) export class HomeDirective { constructor
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;
}
}
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');
}
}
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);
}
}
有人能帮我吗?我是angular 2和typescript的新手。我的密码可能错了。如果我的密码错了,请纠正我
PS:尽管typescript抛出了这个错误,但这段代码按照我的要求工作(在开发版本中)。但是不能做prod-build
谢谢您可以写:
(<ChildComponent>componentRef.instance).close.subscribe
(componentRef.instance).close.subscribe
或
(componentRef.instance).close.subscribe
(<any>componentRef.instance).close.subscribe