Search code examples
angularangular-dynamic-components

Best way to dynamically add elements in Angular side by side


I am creating an app which has an API that returns different number of objects in an array depending on the variable that I send him. Depending on how many objects are returned I want to draw that many circles side by side in a row, max 10 circles in one row. Each returned object is carrying info about circle color, id, name. So, if the API returns 20 objects I want to draw 20 circles ( 2 rows), color them in appropriate color which comes with the object, assign them an ID in HTML and a name. What is the best way to dynamically add elements in Angular depending on the size of the returned array from an API?


Solution

  • You could use template injection:

    <div *ngFor='let item of itemsArray' 
         [id]='item.id_key' 
         [ngStyle]="{'background-color': item.color}">
    {{ item.name }}
    </div>
    

    Or you could use the renderer2 class, and dynamically createElement() and appendChild().

    Both approaches are valid, it comes down to personal preference.