How would I dynamically change bootstrap col based on variables and determine when to add row?

Viewed 190

I need to change how many columns a row has based on it's already sorted array.

The bottom example is the result I want. The Comedies need to be two rows. Action 3. And horror only one but I can't seem to figure out how to do that with Typescript

  var movies = [
    { title: 'movie 1', genre: 'comedy' },
    { title: 'movie 2', genre: 'comedy' },
    { title: 'movie 3', genre: 'action' },
    { title: 'movie 4', genre: 'action' },
    { title: 'movie 5', genre: 'action' },
    { title: 'movie 6', genre: 'horror' }
  ];
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<div *ngFor="let movie of movies; let index = index">
  <div class="form-row">
    <div class="col">{{movie.title}}</div>
  </div>
</div>

<div class="form-row">
  <div class="col-3">Movie 1</div>
  <div class="col-3">Movie 2</div>
  <div class="col-3">Movie 3</div>
</div>
<div class="form-row">
  <div class="col-6">Movie 4</div>
  <div class="col-6">Movie 5</div>
</div>
<div class="form-row">
  <div class="col-3">Movie 6</div>
</div>

1 Answers

in your component add an array of generes

generes = ['action', 'comedy', 'horror']
// if it's dynamic you can get it from movies

then in your template you can loop over generes and movies like this:

<div class="form-row" *ngFor="let genere of generes>
    <ng-container *ngFor="let movie of movies;">
        <div *ngIf="movie.genere === genere"
        [ngClass]="{'col-3': genere !== 'action', 'col-6': genere === 'action'}">
        {{movie.title}}
        </div>
    </ng-container>
</div>

[ngClass] lets you to assign a class to an element based on a specific condition

here is used to host the ngFor directive. because we cannot use ngFor and ngIf in a same element.

Related