Extending Angular 5 Component Using Metadata

When my project used Angular 2 and Angular 4, I was able to use this useful decorator so that the component extends another component:

// Modified from https://medium.com/@ttemplier/angular2-decorators-and-class-inheritance-905921dbd1b7#.s9pf0649f
// by Thierry Templier.

import { Component } from '@angular/core';

export function ComponentExtender(annotation: any): ((target: Function) => void) {
  return function(target: Function): void {
    let parentTarget = Object.getPrototypeOf(target.prototype).constructor;
    let parentAnnotations = Reflect.getMetadata('annotations', parentTarget); // TODO: Doesn't work in Angular 5, returns undefined.
    let parentAnnotation = parentAnnotations[0];

    Object.keys(parentAnnotation).forEach(key => {
      if (parentAnnotation[key]) {
        if (!annotation[key]) {
          annotation[key] = parentAnnotation[key];
        }
      }
    });

    let metadata = new Component(annotation);

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

With this, you can create a component class that extends another component class using @ComponentExtender instead of @Component, and inherits things from the superclass, such as template and style, if these things do not need to be changed in the subclass component.

Now this no longer works when I migrated the project to Angular 5. Annotation metadata is undefined.

Perhaps this is due to the compilation of AOT (although I did not select this option)? Can anyone think of how to animate what this decorator used for Angular 2 and Angular 4?

+4
source share
2

target['__annotations__'][0].

'__paramaters__' '__prop__metadata__', . decorators.ts

. Angular Blog, , .

Disclaimer: this is a hack and implementation detail, so it should never be used in production code!

+1
source

Source: https://habr.com/ru/post/1689102/


All Articles