首页 文章

扩展angular2组件装饰器

提问于
浏览
2

使用角度2.0.0-beta.8,我创建了一些自定义装饰器,扩展了@Component装饰器 .

为了使我使用此代码:

import {..., View } from 'angular2/core';

...

export var MyCustomComponent:ComponentFactory =
    <ComponentFactory>makeDecorator(MyCustomComponentMetadata, (fn:any) => fn.View = View);

现在,使用角度2.0.0-beta.12,“视图”装饰器已被删除,因此导入会引发错误,因为“angular2 / core”没有导出的成员“View” .

我应该如何创建自定义组件装饰器?

2 回答

  • 4

    你可以做

    import {Component} from 'angular2/angular2';
    import {MyCustomComponentMetadata} from ...;
    
    export function MyCustomComponent(config: MyCustomComponentMetadata) {
      return function(cls) {
        var annotations = Reflect.getMetadata('annotations', cls) || [];
        annotations.push(new Component(config));
        Reflect.defineMetadata('annotations', annotations, cls);
        return cls;
      };
    };
    
  • 1

    Angular 6不再使用Reflection来定义组件的元数据 . 要覆盖内置组件装饰器,您可以执行以下操作,

    import { Component } from '@angular/core';
    import componentRegistry from './ComponentRegistry';
     
    function MyComponent(args: any = {}): (cls: any) => any {
      const ngCompDecorator = Component(args);
     
      return function (compType: any) {
        ngCompDecorator(compType);
        args.type && componentRegistry.register(args.type, compType, args.model);
      }
    }
     
    export default MyComponent;
    

    它们的元数据存储在组件构造函数中名为 __annotations__ 的静态属性中 . 要了解更多信息,请查看here

相关问题