user3481798
user3481798

Reputation: 257

Repeating use of ng-content

I have an angular 2 component (my-panel) that will display the supplied content using ng-content. I also want to display that same content in an expanded modal, however it appears that I can only reference ng-content once in the template.

Is it possible to reference the panel content more than once in the template, thus avoiding the need to pass the same content more than once and needing to specifically reference each using selectors with ng-content?

Thanks in advance.

my-panel template:

<div class="panel panel-default">
    <!-- non-expanded panel -->
    <div class="panel-body">
        <ng-content></ng-content>
    </div>

    <button data-toggle="modal" data-target="#myModal">Expand</button>

    <!-- Modal -->
    <div id="myModal" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-body">
                    <ng-content></ng-content>  <-- content not displayed
                </div>
            </div>
        </div>
    </div>
</div>

desired my-panel usage:

<my-panel>
 <p>my panel content</p>
</my-panel>

Upvotes: 6

Views: 3759

Answers (2)

Anmol
Anmol

Reputation: 683

this trick you can use If you want to use ng-content multiple times-

(The basic idea is we are deligating multiple uses to ng-container and ng-template combination.)

Replace every occurrence of ng-content with this below line-

<ng-container *ngTemplateOutlet="theContent"></ng-container>

Put this at the end of the code

<ng-template #theContent>
    <ng-content></ng-content>
</ng-template>

[Tested on: Angular 12]

Upvotes: 2

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657318

There should be only one <ng-content> without a select="selector" attribute. All content that doesn't match the selector of other <ng-content> elements will be transcluded to the first <ng-content> element without a select attribute.

What you can use instead is

<div *ngFor="let x of y" *ngForTemplate="someTemplateRef"

Plunker example

update

Above syntax seems to break in Angular2 final.

Use instead

<template ngFor let-x [ngForOf]="y" [ngForTemplate]="someTemplateRef">
  <div *ngFor="let x of y" *ngForTemplate="someTemplateRef">
</template>

This might also work (not tried)

<div *ngFor="let x of y template:someTemplateRef"

Upvotes: 1

Related Questions