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

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;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)