I have a child component FileUploadComponent that can be used by multiple parent component. The FileUploadComponent has an output that I want to ensure it's handled by ALL parent components.
How can I throw an exception, from the FileUploadComponent, if the output is not handled by one of the parent ?
What I mean by "handled by the parent":
<app-file-upload #campaignFiles
...
(documentsLoaded)="onDocumentsLoaded($event)">
</app-file-upload>
Thanks for your help.
CodePudding user response:
You can check the observed
property of the EventEmitter:
ngAfterViewInit() {
if (this.myOutput.observed) {
// we are fine
} else {
// we have a problem
}
}
(Or alternatively this.myOutput.observed.length, but it's deprecated. Depends on the version of RxJS).
Here's a stackblitz: https://stackblitz.com/edit/angular-mtkweq?file=src/app/hello.component.ts
CodePudding user response:
You can do a hack using the selector like this:
@Component({
selector: 'app-file-upload[documentsLoaded]',
...
})
CodePudding user response:
Thanks all for your help. To anyone coming to this post, based on the accepted answer, I'm throwing an error a toast containing the parentComponent name (to whom the output is not handled) and the child component name (to know where to fix the parent component implementation)
ngAfterViewInit() {
// with newer version of RxJS, use observed i/o observers.length as get deprecated
if (this.documentsLoaded.observers.length == 0) {
const onComponent = this.activatedRoute.snapshot.routeConfig.component.name;
const error = `The parent component '${onComponent}' should handle the output 'documentsLoaded' emitted by its child component ${FileUploadComponent.name}`;
this.toastr.error(error, 'Bad implementation', { disableTimeOut: true, progressBar: false });
throw error;
}
}