angularflexboxangular-directive

*ngFor Changes the alignment of Components


When I render my components just as in a div they are aligned horizontally, which I specified by adding the flexbox container class to the div in which they are stored in.

<div class="flexbox-container" >
  <app-card></app-card>
  <app-card></app-card>
  <app-card></app-card>
</div>

Here is the CSS:

.flexbox-container{
    display: flex;
    justify-content: center;
}

enter image description here

However, when I add an input property to these components, and use a loop to display them they are stacked on top of each other.

<div class="flexbox-container" *ngFor="let title of titles" >
  <app-card title={{title}}></app-card>
</div>

enter image description here

My question is how can I change this so my components are aligned horizontally like they were before instead of vertically?


Solution

  • That is because you are adding the ngFor in wrong place. The way you are coding it is creating 4 divs and placing a single element in each one. The code should be

    <div class="flexbox-container">
         <app-card *ngFor="let title of titles" title={{title}}></app-card>
    </div>
    

    Please mark it as answer if it helps. Happy Coding :)