1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Pass template and context through several child components Angular

Discussão em 'Angular' iniciado por TCH, Outubro 16, 2024.

  1. TCH

    TCH Guest

    I recently faced an issue when trying to pass a template through several Angular components.
    I was not able to pass the template declared in the parent and its context to the child component at last depth (here child-depth2).

    <parent> // declare the template and its context
    <child-depth1>
    <child-depth2> // use the template


    Trying different things (ng-content, template as input,...) I ended up with this code that seems to work in my case.
    Is it the right way to do so ? Is there other way to pass a template and its context through several child components ?

    ParentComponent

    <child-depth1>
    <ng-template #initialItemTemplate let-item>
    <span>{{ item.label }}</span>
    </ng-template>
    </child-depth1>


    ChildDepth1Component

    @ContentChild("initialItemTemplate") readonly initialItemTemplate?: TemplateRef<unknown>;


    <child-depth2>
    <ng-template #itemTemplate let-item>
    <ng-container *ngTemplateOutlet="initialItemTemplate; context: { $implicit: item }">
    </ng-container>
    </ng-template>
    </child-depth2>


    ChildDepth2Component

    @ContentChild("itemTemplate") readonly itemTemplate?: TemplateRef<unknown>;


    @for (item of items; track item.id) {
    <ng-container *ngTemplateOutlet="itemTemplate; context: { $implicit: item }">
    </ng-container>
    }

    Continue reading...

Compartilhe esta Página