Home > Enterprise >  Dynamically add div container inside ngFor?
Dynamically add div container inside ngFor?

Time:03-05

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 >
      </ng-container>
    
      <div >
          
        <div  mdbWavesEffect>
          <img src="https://i.imgur.com/IfoRpDP.png"  alt="Sample project image">
          <a>
            <div ></div>
          </a>
        </div>
    
        <mdb-card-body >
          <h4>
            <strong>Title of the news</strong>
          </h4>
          <p >Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe
            eveniet
            ut et voluptates repudiandae.
          </p>
          <a mdbBtn color="indigo" size="sm"  mdbWavesEffect>
            <mdb-icon far icon="clone" ></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 ></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?

CodePudding user response:

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  *ngFor="let threeCourses of coursesToDisplay">
    <div  *ngFor="let course of threeCourses">
        // ...content
    </div>
</div>
  • Related