I\'m doing some tests with Angular 2 and I have a directive (layout-item) that can be applied to all my components.
Inside that directive I want to be able to read s
Forget about the Service, there's a simpler form of doing this
Option 1 (Not what you need, but it may be useful for other users)
HTML
Three different components, all of the share the same layout-item
property.
Directive
@Directive({
selector : '[layout-item]',
properties: ['myParentConfig: my-parent-config'] // See the components for this property
})
export class MyDirective {
constructor() {
}
onInit() {
console.log(this.myParentConfig);
}
}
Pretty straightforward, not much to explain here
Component
@Component({
selector : 'my-component',
properties : ['myConfig: layout-item']
})
@View({
template : ``,
directives : [MyDirective]
})
export class MyComponent {
constructor() {
}
}
I'm pretty sure that you understand this, but for the sake of a good answer I will explain what it does
properties : ['myConfig: layout-item']`
This line assigns the layout-item
property to the internal myConfig
property.
Component's template
template : ``,
We are creating a my-parent-config
property for the directive and we assign the parent's config to it.
As simple as that! So now we can add more components with (pretty much) the same code
Second component
@Component({
selector : 'my-second-component',
properties : ['myConfig: layout-item']
})
@View({
template : ``,
directives : [MyDirective]
})
export class MySecondComponent {
constructor() {
}
}
See? Was much easier than my idea of using services (awful but 'working' idea).
With this way it is much simpler and cleaner. Here's the plnkr so you can test it.
(It wasn't what you need :'( )
UPDATE
Option 2
For what I understood of your updated question is that you need a reference to the component, so what I came up with is pretty similar to my original answer
What I did :
LayoutItem
directive (which was injected in each component, not at top-level)@Component({
selector : 'my-cmp-a',
properties : ['ref: ref']
})
@View({
template : '',
directives : [LayoutItem]
})
@YourCustomAnnotation({})
export class MyCmpA {
constructor() {
}
}
@Directive({
selector : '[layout-item]',
properties : ['reference: parent-reference']
})
export class LayoutItem {
constructor() {
}
onInit() {
console.log(this.reference.constructor);
Reflector.getMetadata("YourCustomAnnotation", this.reference.constructor);
}
}
Use this plnkr to do your tests.