How to access the Component on a Angular2 Directive?

Discussão em 'Angular' iniciado por jpsfs, Março 28, 2025.

  1. jpsfs

    jpsfs Guest

    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 some metadata defined on the component but for that I need to access the component's reference.

    I have tried the following approach but I was unable to get what I need. Does any one has a suggestion?

    @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.
    }
    }

    Continue reading...

Compartilhe esta Página