Consider the following component:
@Component({
selector: 'app-test'
template: 'Hello!'
}}
export class TestComponent {
@Output() readonly selectionChange = new EventEmitter<SomeTypeHere>();
}
With the call:
<app-test (selectedChange)="selectedChangeHandler($event)"></app-test>
Note that I've written selectedChange
instead of the correct output name selectionChange
. Angular 9 with the flag strictTemplates
enabled didn't help me at all. It failed silently. The interesting part is that if I do the same thing for @Input
, the app catch the error(s) and doesn't compile.
Is there any way to throw an error if I try to "listen" an inexistent @Output
?
There is no error thrown because the event binding in Angular is used not only with @Output
s and EventEmitter
s, but also to listen to the DOM events such as click
, keyup
, etc. It could even be used to listen to custom events. For example, if you create and emit a custom event in the child component:
constructor (private el: ElementRef) {}
ngOnInit(): void {
const domEvent = new CustomEvent('selectedChange', { custom: true });
this.el.nativeElement.dispatchEvent(domEvent);
}
Then in the parent component you can catch it by its name:
<app-test (selectedChange)="selectedChangeHandler($event)"></app-test>
Angular uses target.addEventListener(type, listener [, options]); internally (you can make sure of it looking at the links below), where type
could be any string.
That's why it doesn't throw any exception if it doesn't find matching @Output
s.
listenToElementOutputs
DefaultDomRenderer2.listen
EventManager.addEventListener
DomEventsPlugin.addEventListener
This should work for you.
ngOnInit() : void {
if(this.selectionChange.observers.length > 0){
console.log("Nice coding");
}else{
console.log("Something is wrong!!");
}
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