Suppose I have this EventEmitter in a child component:
export class ImageUploadComponent {
...
@Output() imageDataEvent: EventEmitter<string> = new EventEmitter<string>();
...
}
This child component, depending on what happens may emit something or generate an error:
...
this.imageDataEvent.emit('good');
...
this.imageDataEvent.error('wrong');
The parent component listens to it through event binding:
<app-image-upload (imageDataEvent)="onImageUpload($event)"></app-image-upload>
When 'good' is emitted, onImageUpload is called on parent component and $event contains 'good'.
How to handle the case of 'wrong'? How can I know when the event is an error? How exactly event binding works for good/bad events?
Angular's EventEmitter
s are actually an extension of Observable
s.
It's been said that it's generally best practice to not handle errors in @Output
s. However, taking advantage of Observable
error streams can lead to some pretty elegant code, and having access to Observable
operators has some very obvious benefits.
The only difference is that Angular's template binding to an Output
event handles the Observable
subscription to the EventEmitter
internally. The solution is to forego the template binding and just subscribe to the component property manually:
<app-image-upload #upload></app-image-upload>
in your parent component:
@ViewChild('upload') upload: AppImageUploadComponent;
ngAfterViewInit() {
this.upload.imageDataEvent.subscribe(
event => console.log('Emission!'),
err => console.error(`D'oh!`),
() => console.log('Complete!')
);
}
This also allows you to use catch
or any other Observable operators that you'd need.
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