使用元数据扩展Angular 5组件 [英] Extending an Angular 5 component using metadata

查看:66
本文介绍了使用元数据扩展Angular 5组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的项目使用Angular 2和Angular 4时,我能够使用此有用的修饰符来使组件扩展另一个组件:

When my project was using Angular 2 and Angular 4, I was able to use this useful decorator for making a component extend 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);
  };
}

这样,您可以使用@ComponentExtender而不是@Component来创建扩展另一个组件类的组件类,并从超类继承模板和样式等内容,如果这些内容不需要在子类组件中进行更改

With this you could create a component class that extended an another component class, using @ComponentExtender instead of @Component, and inherit things from the superclass like the template and style if those things did not need to be changes in the subclass component.

既然我已经将项目移至Angular 5,这将不再起作用.注释元数据未定义.

This no longer works now that I've moved my project to Angular 5. The annotations metadata is undefined.

这也许与AOT编译有关(即使我没有选择该选项)?谁能想到一种方法来恢复此装饰器过去对Angular 2和Angular 4所做的工作?

Does this perhaps have something to do with AOT compilation (even though I haven't selected that option)? Can anyone think of a way to revive what this decorator used to do for Angular 2 and Angular 4?

推荐答案

您可以将组件的注释保存在单独的变量中,并将其与组件一起导出,因此无需从组件的元数据中检索它. 这是一个小例子,希望对您有帮助.

You can save component's annotation in separate variable and export it together with your component, so you don't need to retrieve it from component's metadata. here is small example, hope it would help you.

https://stackblitz.com/edit/angular-bxbpwr?embed=1&file=app/asignAnnotations.ts

这篇关于使用元数据扩展Angular 5组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆