Angular 7 flexbox with ngFor

Asked by At

I am trying to use flexbox inside a ngFor loop to get data in columns. Flexbox wrap property is on to show data in rows for smaller screens. But data is showing in rows even on bigger screens. My code is

<div class="main" *ngFor="let hero of heros">
  <div class="child"><mat-checkbox color='primary'>{{hero.name}}</mat-checkbox></div>
</div>

css is

.main {
    width: 90%;
    list-style-type: none;
    margin: 0.5em;
    padding: 0.5em;
    display: flex;
    flex-wrap: wrap;
}

.child {
    width: 400px;
}

heros object is

heros = [
    {id: 1, name: 'Superman'},
    {id: 2, name: 'Batman'},
    {id: 5, name: 'BatGirl'},
    {id: 3, name: 'Robin'},
    {id: 4, name: 'Flash'}
  ];

enter image description here

3 Answers

0
Shadab Faiz On Best Solutions

You did were small mistake. You set the class main at the wrong place. Try this:

// html
<div class="main">
  <div *ngFor="let hero of heros">
  <div class="child">
    {{hero.name}}
  </div>
</div>
</div>


// css
.main {
    width: 90%;
    list-style-type: none;
    margin: 0.5em;
    padding: 0.5em;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    background: red;
}

.child {
    width: fit-content;
    max-width: 100%;
    background: blue;
    margin: 1% 0px;

}

this will give a clear picture of how things are rendering.

0
Boy Abdullah On

Try using media queries.

.main {
    width: 90%;
    list-style-type: none;
    margin: 0.5em;
    padding: 0.5em;
    display: flex;
}

.child {
    width: 400px;
}


/* On screens that are 768 or less */
@media screen and (max-width: 768px) {
  .main {
    width: 90%;
    list-style-type: none;
    margin: 0.5em;
    padding: 0.5em;
    display: flex;
    flex-wrap: wrap;
}

.child {
    width: 400px;
}

}
0
Chiến Nghê On

First, move the ngFor to the child element, it should not repeat the main container

<div class="main" >
  <div class="child" *ngFor="let hero of heros"><mat-checkbox color='primary'>{{hero.name}}</mat-checkbox></div>
</div>

Second, change to flex-wrap to no-wrap in css

.main {
    width: 90%;
    list-style-type: none;
    margin: 0.5em;
    padding: 0.5em;
    display: flex;
    flex-wrap: no-wrap;
}

.child {
    width: 400px;
}

The you will see the elements in horizontal line as image below

enter image description here