1

I need to repeat a component inside another component, let's say:

Component A only accepts, inside its ng-content, a component of type B.

doing something like:

<component-a>
    <ng-template ngFor [ngForOf]="items">
        <component-B></component-B>
    </ng-template>
</component-a>

or this:

<component-a>
    <ng-container *ngFor="let item of items">
        <component-B></component-B>
    </ng-container>
</component-a>

does not work...

I can't modify component-a nor compoenent-B and these approaches doesn't render the component-B...

Any ideas how to overcome this?

Thanks.

PS: I may need to add multiple component-B for each item.

  • Don't you mean `ng-container` not `ng-template`? I wrote up the difference, as I kept getting it wrong: https://blog.jonrshar.pe/2017/May/20/angular-ng-elements.html – jonrsharpe Oct 16 '17 at 13:31
  • pass the array as parameter to inner component, repeat it in the template of the inner component. – omeralper Oct 16 '17 at 13:37
  • question edited. I can't modify component-b. – Sergio Figueiredo Oct 16 '17 at 13:39
  • you need to replace `ng-template` with `ng-container`. – phil294 Oct 16 '17 at 14:29
  • @Blauhirn As I stated in the question, I already tried with ng-container too. But thanks anyway. – Sergio Figueiredo Oct 16 '17 at 14:50
  • @SergioFigueiredo I am really sorry, should have read the entire question. What do you mean by "can't modify"? - your code looks fine to me. The only reason I can see is `items` being empty (I guess your console doesn't give any errors either?) – phil294 Oct 16 '17 at 15:42
  • @Blauhirn I'm using an external framework, and both component-a and component-b are not mine, if I use something like the example from Jason below it works, but with ng-container or ng-template it does not... no errors, but does not render the items either – Sergio Figueiredo Oct 17 '17 at 07:45
  • so `component-a` template somewhere has a `` inside. One would expect `ng-container` not to affect the requirement. This looks either like bad design or an actual bug by the Angular framework to me. Maybe you could set up a plunker and open an issue on their github page. Good luck – phil294 Oct 17 '17 at 16:32
  • unfortunately, the entire functionality is [still not documented](https://github.com/angular/angular/issues/17983). – phil294 Oct 17 '17 at 22:21
  • I have created a plunker demo: https://plnkr.co/edit/7jlcpU0Wxxo6YxtrY66l?p=preview you can see the intended result on app.component.html – Sergio Figueiredo Oct 18 '17 at 13:20

2 Answers2

0

I would normally expect something as simple as the below to work:

<component-a>
    <component-B *ngFor="let item of items">
    </component-B>  
</component-a>

Or with the ngForOf syntax, doesn't really matter. Is there any more info you could give in order to better pinpoint where the issue might be?

Jason
  • 61
  • 4
0

Solved! by using

ngProjectAs="selector" 

attribute on ng-container!