Gigitsu
Gigitsu

Reputation: 653

Extending angular2 component decorator

With angular 2.0.0-beta.8 I've created a couple of custom decorator that extends the @Component decorator.

To make that I've used this code:

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

...

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

Now, with angular 2.0.0-beta.12, the 'View' decorator has been dropped so the import throw an error because 'angular2/core' has no exported member 'View'.

How I'm supposed to create a custom component decorator?

Upvotes: 2

Views: 2732

Answers (2)

VJAI
VJAI

Reputation: 32768

Angular 6 no more uses Reflection to define metadata for components. To override the built-in component decorator you could do something like below,

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;

They metadata is stored in a static property called __annotations__ in the component's constructor. To know more about this please check here

Upvotes: 1

Luca
Luca

Reputation: 4273

You can do

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;
  };
};

Upvotes: 4

Related Questions