1

I have the BaseComponent with template set. I want to use the same template HTML in a component extending base one. I know class inheritance in Angular2 is only for classes and not for decorators. So it looks like I need a new decorator which will find parent class and all its decorators and apply to current class. Some properties of decorators should be possible to change (like selector for @Component).

koral
  • 2,807
  • 3
  • 37
  • 65

1 Answers1

1

You could create your own component that create and register component metadata leveraging the one from its parent class.

Something like that:

export function CustomComponent(annotation: any) {
  return function (target: Function) {
    var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
    var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);

    var parentAnnotation = parentAnnotations[0];
    Object.keys(parentAnnotation).forEach(key => {
      if (isPresent(parentAnnotation[key])) {
        annotation[key] = parentAnnotation[key];
      }
    });
    var metadata = new ComponentMetadata(annotation);

    Reflect.defineMetadata('annotations', [ metadata ], target);
  }
}

You can use it this way:

@Component({
  template: `
    (...)
  `
})
export class ParentComponent {
}

@CustomComponent({
  selector: 'test'
})
export class ChildComponent extends ParentComponent {
}

See this question for more details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • I use Angular beta rc1. `ComponentMetadata`, `Reflect.getMetadata()`, `isPresent()` and `Reflect.defineMetadata()` are unknown. What should I import? – koral Jun 09 '16 at 14:26