¿Cómo acceder al componente en una directiva Angular2?
Estoy haciendo algunas pruebas con Angular 2 y tengo una directiva (elemento de diseño) que se puede aplicar a todos mis componentes.
Dentro de esa directiva quiero poder leer algunos metadatos definidos en el componente pero para eso necesito acceder a la referencia del componente.
He intentado el siguiente enfoque pero no he podido obtener lo que necesito. ¿Alguien tiene una sugerencia?
@Component({...})
@View({...})
@MyAnnotation({...})
export class MyComponentA {...}
// Somewhere in a template
<myComponentA layout-item="my config 1"></myComponentA>
<myComponentB layout-item="my config 2"></myComponentA>
// ----------------------
@ng.Directive({
selector: "[layout-item]",
properties: [
"strOptions: layout-item"
],
host: {
}
})
export class LayoutItem {
// What works
constructor(@Optional() @Ancestor({self: true}) private component: MyComponent1) {
// with the constructor defined like this, component is defined ,with myComponent1 instance.
Reflector.getMetadata("MyAnnotation", component.constructor); // > metadata is here!
}
// What I needed
constructor(@Optional() @Ancestor({self: true}) private component: any) {
// This will crash the app. If instead of any I specify some other type, the app will not crash but component will be null.
// This directive can be applied to any component, so specifying a type is not a solution.
}
}