2016-06-08 5 views
0

달성하고자하는 것은 EventEmitter@Output으로 장식하여 반복하려는 주어진 구성 요소 인스턴스입니다.각도 2로 @Output()으로 장식 된 모든 EventEmitter를 반복 할 수 있습니까?

예 :

내 구성 요소

@Component({ 
    moduleId: module.id, 
    selector: "my-component", 
    template: "<h1>My Component!!" 
    }) 
    export class MyComponent{ 
    @Output() emitter1: EventEmitter<any> = new EventEmitter<any>(); 
    @Output() emitter2: EventEmitter<any> = new EventEmitter<any>(); 
    } 

그래서 아래와 같이 동적으로 구성 요소를로드하고 말할 수,

this._cr.resolveComponent(MyComponent).then(cmpFactory => { 
     this.testComponentContainer.clear(); 
     let instance: any = this.testComponentContainer.createComponent(cmpFactory).instance; 

     // Here I want to iterate over EventEmitter dynamically 
     // So that I may bind to both emitter1 and emitter2 
    }); 

내가이 작업을 수행 할 수

? 미리 감사드립니다 !!

답변

1

propMetadata 메타 데이터를 보면 장식 된 출력을 찾을 수 있습니다. 여기

는 샘플입니다 마두 란잔에 의해

this._cr.resolveComponent(MyComponent).then(cmpFactory => { 
    this.testComponentContainer.clear(); 
    let instance: any = this.testComponentContainer.createComponent(cmpFactory).instance; 

    var propMetadata = Reflect.getMetadata('propMetadata', MyComponent); 
    var outputs = propMetadata.filter(metadata => { 
     return (metadata instanceof OutputMetadata); 
    }); 

    outputs.forEach(output => { 
     output.subscribe(event => { 
     // handle event 
     }); 
    }); 

    // Here I want to iterate over EventEmitter dynamically 
    // So that I may bind to both emitter1 and emitter2 
}); 

업데이트 , 그러나 제대로 아래와 같이 사용하라고 암시 위의 코드에 문제가있다

this._cr.resolveComponent(componentToTest).then(cmpFactory => { 
     this.testComponentContainer.clear(); 
     let instance: any = this.testComponentContainer.createComponent(cmpFactory).instance; 

     let propMetadata: any = Reflect.getMetadata('propMetadata', componentToTest); 
     let outputs: any = []; 

     for (let key in propMetadata) { 
      if (propMetadata.hasOwnProperty(key)) { 
       if (propMetadata[key].length > 0) { 
        let _hasOutput = propMetadata[key].filter(metadata => { 
         return (metadata instanceof OutputMetadata); 
        }); 

        if (_hasOutput && _hasOutput.length > 0) { 
         outputs.push(key); 
        } 
       } 
      } 
     } 

     outputs.forEach(output => { 
      instance[output].subscribe(event => { 
       // Logic to use event data.. 
      }); 
     }); 
    });