2015-10-30 60 views
9

在組件的ngOnInit方法中,@Input值已被綁定,因此您可以檢查組件上的這些屬性,但似乎沒有辦法檢查@Output事件綁定。我希望能夠知道@Output是否在組件上連線。有沒有辦法從Angular 2的組件中檢查@Output線?

(採用了棱角分明2 Beta 2和打字稿)

import {Component, Output, EventEmitter} from 'angular2/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> 
    } 
} 

回答

16

相同的方法,user1448982但不使用即意味着ObservableWrapper是平臺的代碼,不會通過API暴露。

(採用了棱角分明2 RC1和打字稿)
注:這只是開始,從2.0.0-beta.16和更大

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

工作ObservableWrapper.hasSubscribers方法做這行在內部,所以你可以在這裏做同樣的事情。

當使用打字稿如果角度過最終從Subject改變EventEmitter你會得到一個transpile時錯誤(這是部分Observable,因此.observers屬性)。

3

下面的代碼應該工作:

import {Component, Output, EventEmitter, OnInit} from 'angular2/core'; 
import {ObservableWrapper} from 'angular2/src/facade/async'; 

@Component({ 
    selector: 'sample', 
    template: `<p>a sample</p>` 
}) 
export class SampleComponent implements OnInit { 
    @Output() cancel: EventEmitter<any> = new EventEmitter(); 

    private isCancelUsed: boolean; 

    ngOnInit(): void { 
     this.isCancelUsed = ObservableWrapper.hasSubscribers(this.cancel); 
    } 
} 
+0

不要依賴這個。 Angular團隊不保證'EventEmitter'會繼續擴展'Observable' –

相關問題