6

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>
user3481798
  • 247
  • 2
  • 11

2 Answers2

1

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"
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    Thanks for this response. What I'm essentially trying to do is clone the data passed to my-panel, but it doesn't appear that I can do that without cloning the data myself by passing it in twice and then selecting each. The data passed in will eventually be a heavy weight component populated by a lot of network calls, and I'm trying to avoid duplicating all of that just to show the same content in an expand modal. But if I'm understanding you correctly, I can't do that. – user3481798 Jun 07 '16 at 17:12
  • @user3481798 did you figure out a better way? – Pedro A Feb 05 '22 at 20:43
1

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]

Anmol
  • 490
  • 6
  • 8