gpt4 book ai didi

angular - Typescript 错误 - ComponentRef 上的 TS2339

转载 作者:搜寻专家 更新时间:2023-10-30 21:30:32 26 4
gpt4 key购买 nike

我遇到 typescript 错误

error TS2339: Property 'close' does not exist on type '{}'

我遇到问题的代码:-

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);
}
}

谁能帮帮我?我是 Angular 2 和 typescript 的新手。我的编码可能是错误的。如果我的编码有误,请纠正我。

PS:即使 typescript 抛出了这个错误,这段代码也能按我想要的方式工作(在开发版本中)。但不能进行产品构建

谢谢

最佳答案

你可以这样写:

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

或者

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

关于angular - Typescript 错误 - ComponentRef 上的 TS2339,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39580484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com