I'm trying to call functions from external components on a custom selector. I've found a method to achieve this, but it won't recognize any of the variables from the component. This is what I've done:
Selector (declared as an entry component):
HTML:
<button (click)="addCertificate(searchInput)">Add</button>
TS:
constructor(public sharedService: SharedFilterService ) {
}
public addCertificate(payload: any) {
console.log("Step 1") // This is executed
if (this.sharedService.add_LicenceComponent) {
console.log("Step 2") // This one too
this.sharedService.add_LicenceComponent(payload);
}
}
Service (declared as a provider):
TS:
@Injectable()
export class SharedFilterService {
public add_LicenceComponent: any;
constructor() { }
}
And finally the component (Licence) where I can't reach any variable:
TS:
constructor(public dialogService: DialogService, public sharedService: SharedFilterService) {
this.sharedService.add_LicenceComponent = this.addLicence;
}
addLicence(licence: any): void {
console.log("Step 3") // Printed too
this.dialogService.openDialog(DialogComponent, licence).afterClosed().subscribe(); // Here I get this: ERROR TypeError: Cannot read property 'openDialog' of undefined
}
The service is just a mediator. I'm using a selector (the buttom calling addCertificate) inside of the Licence component
Assign function for add_LicenceComponent
of sharedService instead returning void.
Another thing is your getting TypeError because of service not initialised while trying to access it in constructor. Move it to ngOnInit() and do check do whether you added them in providers
You need to do some modifications in your component code like below,
constructor(public dialogService: DialogService, public sharedService: SharedFilterService) { }
ngOnInit() {
this.sharedService.add_LicenceComponent = this.addLicence;
}
addLicence(licence: any) {
console.log("Step 3") // Printed too
return (licence) => this.dialogService.openDialog(DialogComponent, licence).afterClosed().subscribe();
}
You can check sample impl in this stackblitz