Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if output is present on component

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?

like image 394
dev_054 Avatar asked Feb 23 '20 03:02

dev_054


2 Answers

There is no error thrown because the event binding in Angular is used not only with @Outputs and EventEmitters, 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 @Outputs.

listenToElementOutputs

DefaultDomRenderer2.listen

EventManager.addEventListener

DomEventsPlugin.addEventListener

like image 180
Kirill Simonov Avatar answered Nov 07 '22 20:11

Kirill Simonov


This should work for you.

ngOnInit() : void {
 if(this.selectionChange.observers.length > 0){
   console.log("Nice coding");
 }else{
  console.log("Something is wrong!!");
}
like image 1
Tamajit Avatar answered Nov 07 '22 21:11

Tamajit