Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check for @Output wire up from within a component in Angular?

In the ngOnInit method of a component the @Input values will have been bound so you can check those properties on the component, but there doesn't seem to be a way to check @Output event bindings. I want to be able to know if the @Output was wired up on the component or not.

(using Angular and TypeScript)

import {Component, Output, EventEmitter} from '@angular/core';  @Component({     selector: 'sample',     template: `<p>a sample</p>` }) export class SampleComponent {     @Output() cancel = new EventEmitter();          ngOnInit() {         // would like to check and see if cancel was used         // on the element <sample (cancel)="doSomething()"></sample>          // or not <sample></sample>     } } 
like image 566
Justin Schwartzenberger Avatar asked Oct 30 '15 17:10

Justin Schwartzenberger


People also ask

What is the difference between @input and @output in angular?

@Input() and @Output() give a child component a way to communicate with its parent component. @Input() lets a parent component update data in the child component. Conversely, @Output() lets the child send data to a parent component.

What is event emitter in angular?

๐ŸŽŠ Event Emitters in Angular ๐ŸŽŠData flows into your component via property bindings and flows out of your component through event bindings. If you want your component to notify his parent about something you can use the Output decorator with EventEmitter to create a custom event.


1 Answers

Same approach as user1448982 but without using the ObservableWrapper that is meant to be platform code that is not exposed for use via the api.

(Using Angular 2 RC1 and TypeScript)
Note: This only started working from 2.0.0-beta.16 and greater

import {Component, Output, EventEmitter} from '@angular/core';  @Component({     selector: 'sample',     template: `<p>a sample</p>` }) export class SampleComponent {     @Output() cancel = new EventEmitter();     private isCancelUsed = false;      ngOnInit() {         this.isCancelUsed = this.cancel.observers.length > 0;     } } 

Plunker

The ObservableWrapper.hasSubscribers method does this line internally, so you can just do the same thing here.

When using TypeScript you will get a transpile time error if Angular ever ends up changing the EventEmitter from a Subject (which is part Observable, thus the .observers property).

Update (03 / 2022)

The observers attribute is deprecated since rxjs v7. Instead of checking the length of the observers array, you can now use a boolean that indicates if the subject is in use.

// Old approach this.isCancelUsed = this.cancel.observers.length > 0;  // New approach this.isCancelUsed = this.cancel.observed; 
like image 165
Justin Schwartzenberger Avatar answered Sep 19 '22 17:09

Justin Schwartzenberger