I am facing a typescript error
error TS2339: Property 'close' does not exist on type '{}'
Code where i face issue :-
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');
}
}
and i am invoking 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);
}
}
Can anyone help me out? I am a newbie in angular 2 and typescript. my codings might be wrong. please correct me if my codings are wrong.
PS: Even though typescript throws this error, this code works as i wanted(in dev build). but cant do prod build
Thanks
You can write:
(<ChildComponent>componentRef.instance).close.subscribe
Or
(<any>componentRef.instance).close.subscribe
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With