0

I have the following JSON structure that I want to show using component:

const rootBlock = {
   id: 1,
   fields: [],
   blocks: [{
      id: 2,
      fields: []
      blocks: []
   }]
} as Block;

There is component BlockComponent.

@Input() block: Block;

I want to show all nested component inside one, how to do that using projection?

<app-block>
   <app-block></app-block>
</app-block>
2
  • so what should show the app block? can you share the HTML template? so I can try to create it. Commented Aug 7, 2020 at 11:26
  • Block component has template <div class="block"><div>id: {{block.id}}</div><div class="nestedBlocks"></div></div> Commented Aug 7, 2020 at 11:27

1 Answer 1

2

In your app-block component, keep a ng-content outlet

block.component.html

<h2>Some text</h2>
<ng-content></ng-content>

Using this, whatever you put inside your tag, they will render, including the same component nested inside.

Update:

block.component.ts

@Input() block: Block;

block.component.html

<div class="block">
  <div> 
    id: {{block.id}}
  </div>
  <ng-container *ngIf="block?.blocks?.length">
    <div class="nestedBlocks" *ngFor="let eachBLock of block.blocks">
       <app-block [block]="eachBLock"></app-block>
    </div>
  </ng-container>
</div>

app.component.html

<app-block [block]="rootBlock"></app-block>
Sign up to request clarification or add additional context in comments.

5 Comments

How it looks in templete? Could you extend the answer?
I have dynamic JSON object it can be a lot of nested blocks
I have udated the answer. You can try that.
I need still <ng-content></ng-content>?
No. That should not be required anymore for your case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.