0

我正在编写一个 Angular 库。一个对象包装了一个 Angular 组件实例,这个对象必须订阅组件实例中所有标有Output装饰器的主体。到目前为止,这是我在构造函数中编写的代码:

const componentProperties = Object.keys(this.component.instance);
componentProperties.forEach(property => {
    if (!!Reflect.getMetadata('Output', this.component.instance, property)) {
        //do stuff to subscribe
    }
});

Reflect.getMetadata正在返回 false 还分析角度组件内的属性“testEvent”:

export class Test2Component implements OnInit {
  public text: string;
  @Output() testEvent = new EventEmitter();
  //...
}

我究竟做错了什么?

更新

目前,我使用了这个技巧:

 componentProperties.forEach(property => {
      if (
        this.component.instance.constructor.__prop__metadata__ &&
        this.component.instance.constructor.__prop__metadata__[property]
      ) {
        this.component.instance.constructor.__prop__metadata__[property].forEach(decorator => {
          if (Reflect.getPrototypeOf(decorator)['ngMetadataName'] === 'Output') {
            let eventName = decorator.bindingPropertyName ? decorator.bindingPropertyName : property;
            this.registerEvent(property);
            this.emitters.push(eventName);
          }
        });
      }
    });

非常丑陋,但它的工作原理

4

1 回答 1

0

我找到了一种更好的方法来做同样的事情ComponentFactoryResolver

const factory = componentFactoryResolver.resolveComponentFactory(this.component.componentType);
const eventEmitters = factory.outputs;
eventEmitters.forEach(e => {
  this.registerEvent(e.propName, e.templateName);
  this.emitters.push(e.templateName);
});
于 2020-01-02T09:12:21.357 回答