0

what is the easiest way of dynamically creating a DOM elements in component? I have a model of a tree (items with parentId param) loaded from API and I need to print them out into nested lists like

<ul>
    <li>List item one</li>
    <li>List item two with subitems:
        <ul>
            <li>Subitem 1</li>
            <li>Subitem 2</li>
        </ul>
    </li>
    <li>Final list item</li>
</ul>
Kamil Naja
  • 6,267
  • 6
  • 33
  • 47
Gatekeeper
  • 1,586
  • 3
  • 21
  • 33

2 Answers2

2

You need to use *ngFor to create dom elements dynamically in angular2

<ul>
 <ng-template #recursiveList let-list>
<li *ngFor="let item of list">
  {{item.title}} // just assuming
  <ul *ngIf="item.children.length > 0">
    <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.children }"></ng-container>
  </ul>
</li>
</ng-template>
<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: list }"> </ng-container>
</ul>

You need to change code according to your model

Please check gist

Jayakrishnan
  • 4,232
  • 2
  • 23
  • 35
  • Thanks, I know how to use ngFor but consider my example - items with parentId parameter. How would you create multi-level list this way if you dont know how many child lists it would have? – Gatekeeper Jun 30 '17 at 08:42
  • 2
    @Gatekeeper use recursion: create a TreeNode component that displays a node name, and then uses ngFor to display all its children using the TreeNode component. – JB Nizet Jun 30 '17 at 08:55
  • Oh, thats brilliant. Thank you very much! – Gatekeeper Jun 30 '17 at 11:57
  • @Gatekeeper, I am glad it helped you. Please update and accept it as answer, it might help others – Jayakrishnan Jun 30 '17 at 11:59
1

Structural directives is for you.

This guide looks at how Angular manipulates the DOM with structural directives and how you can write your own structural directives to do the same thing.

Max
  • 463
  • 4
  • 11