Angular: Accessing Parent Directive in Recursive List Rendered with ngTemplateOutlet

Discussão em 'Angular' iniciado por Mike5, Novembro 7, 2024.

  1. Mike5

    Mike5 Guest

    I'm working with a template to display a nested list, like this:

    const tree = [
    { label: "A" },
    { label: "B" },
    {
    label: "C",
    children: [
    { label: "C0" },
    { label: "C1" },
    { label: "C2" },
    ],
    },
    { label: "D" },
    { label: "E" },
    {
    label: "F",
    children: [
    { label: "F0" },
    {
    label: "F1",
    children: [
    { label: "F1-0" },
    {
    label: "F1-1",
    children: [
    { label: "F1-1-0" },
    { label: "F1-1-1" },
    { label: "F1-1-2" },
    ],
    },
    { label: "F1-2" },
    ],
    },
    { label: "F2" },
    ],
    },
    ];


    And here’s my HTML template:

    <ul>
    <ng-template #itemTemplate let-entry>
    <li myDirective>{{ entry.label }}
    <ng-container *ngIf="entry.children && entry.children.length">
    <ul>
    <ng-container *ngFor="let child of entry.children">
    <ng-template *ngTemplateOutlet="itemTemplate; context: { $implicit: child }"></ng-template>
    </ng-container>
    </ul>
    </ng-container>
    </li>
    </ng-template>

    <ng-container *ngFor="let item of tree">
    <ng-template *ngTemplateOutlet="itemTemplate; context: { $implicit: item }"></ng-template>
    </ng-container>
    </ul>


    My goal is to retrieve the parent myDirective instance from a child myDirective instance. In the constructor of myDirective, I tried using:

    @Optional() @SkipSelf() private parentItem?: MyDirective | null;


    This works only when the tree is explicitly rendered, without using a template. Otherwise, the dependency hierarchy seems to be lost.

    So, my question is: How can I obtain a reference to the directive instance of a parent element from within a child element rendered through a template?

    For example, how can I access the directive instance for "F1-1" from within the directive instance of "F1-1-0"?

    Continue reading...

Compartilhe esta Página