htmlangulartwitter-bootstrapangular-ui-bootstrapmdbootstrap

Dynamically add div container inside ngFor?


I would like to implement this html page using MDBootstrap.

Inside my .ts file I have three Courses.

var c1 = Builder(Course).id(1).autor("ASFASF").build();
var c2 = Builder(Course).id(1).autor("ASFASF").build();
var c3 = Builder(Course).id(1).autor("ASFASF").build();
this.courses.push(c1); this.courses.push(c2); this.courses.push(c3);

In html I'm trying to do something like this:

  <ng-container *ngFor="let course of courses; let i = index" >
      <ng-container *ngIf="i === 0 || (i+1) % 3 === 0">
        <div class="row text-center">
      </ng-container>
    
      <div class="col-lg-4 col-md-12 mb-4">
          
        <div class="view overlay rounded z-depth-1 waves-light" mdbWavesEffect>
          <img src="https://i.imgur.com/IfoRpDP.png" class="img-fluid" alt="Sample project image">
          <a>
            <div class="mask rgba-white-slight"></div>
          </a>
        </div>
    
        <mdb-card-body class="mt-3">
          <h4>
            <strong>Title of the news</strong>
          </h4>
          <p class="grey-text">Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe
            eveniet
            ut et voluptates repudiandae.
          </p>
          <a mdbBtn color="indigo" size="sm" class="waves-light" mdbWavesEffect>
            <mdb-icon far icon="clone" class="left"></mdb-icon> View project</a>
        </mdb-card-body>
    
      </div>
    
      <ng-container *ngIf="i === 0 || (i+1) % 3 === 0">
        </div>
      </ng-container>
</ng-container>

What I'm trying to do is, for 0th and every third item, I want to add <div class="row text-center"></div> but all other items must be inside that row container as it can be seen on link I provided. As expected this cannot compile. Any ideas?


Solution

  • Maybe try to chunk the data? Source: https://ourcodeworld.com/articles/read/278/how-to-split-an-array-into-chunks-of-the-same-size-easily-in-javascript

    It may look like this:

    TS

    coursesToDisplay: any[];
    
    constructor() {}
    
    ngOnInit() {
        // ...
        this.coursesToDisplay = chunkArray(this.courses, 3);
    }
    
    chunkArray(myArray, chunk_size){
        var index = 0;
        var arrayLength = myArray.length;
        var tempArray = [];
        
        for (index = 0; index < arrayLength; index += chunk_size) {
            myChunk = myArray.slice(index, index+chunk_size);
            // Do something if you want with the group
            tempArray.push(myChunk);
        }
    
        return tempArray;
    }
    

    HTML

    <div class="row text-center" *ngFor="let threeCourses of coursesToDisplay">
        <div class="col-lg-4 col-md-12 mb-4" *ngFor="let course of threeCourses">
            // ...content
        </div>
    </div>