Home > Mobile >  How can I render two object in div?
How can I render two object in div?

Time:12-25

I have 2 objects with data and I need to restruct the rendering in html. In this image is what I get but in second image is what I need to obtain. Black box is the *ngFor of articles object, respectively red one is *ngFor adsContainer object

<div *ngFor="let article of articles; let i = index;">

<mat-card >
  <div>
    <a >
      {{article.title}}
    </a>
    <a>
      <p>{{article.content}}</p>
    </a>
  </div>

</mat-card>

<div  *ngIf="(i % 7) === 6">
  <div *ngFor="let data of adsContainer">
    <div>
      <h1>{{data.value}}</h1>
    </div>
  </div>
</div>

</div>
  public adsContainer: any = [
    { id: '1', value: 'text value here' },
    { id: '2', value: 'text value here' },
    { id: '3', value: 'text value here' }
  ]
  public articles: any = [
    { id: '1', title: 'title value here', content: 'content here' },
    { id: '2', title: 'title value here', content: 'content here' },
    { id: '3', title: 'title value here', content: 'content here' },
    ........
    { id: '20', title: 'title value here', content: 'content here' },
  ]

CodePudding user response:

Your issue is that you add your ads containers in a loop

<div  *ngIf="(i % 7) === 6">
  <!-- this loop here -->
  <div *ngFor="let data of adsContainer">
    <div>
      <h1>{{data.value}}</h1>
    </div>
  </div>
</div>

what you want is to add only one ad container at a time, in order to do that, you have to rmove the loop

In order to have the three ads show, you'll have to do some math to get the ad index from the article index

something like this :

<div  *ngIf="(i % 7) === 6">
  <div>
    <h1>{{adsContainer[mathFloor(i / 7)].value}}</h1>
  </div>
</div>

note that Math is not available in angular templates, you'll have to redefine floor as a component method

function mathFloor(val) {return Math.floor(val)}

CodePudding user response:

Try to use directly the array , also when you call adsContainer[(parseInt(i / 6)-1)% adsContainer.length, it will always restart the index:

<div *ngFor="let article of articles; let i = index;">
    
  <mat-card >
    <div>
      <a >
        {{article.title}}
      </a>
      <a>
        <p>{{article.content}}</p>
      </a>
    </div> 
  
  </mat-card>
  
  <div  *ngIf="(i % 7) === 6">
    <div>
      <div>
        <h1>{{adsContainer[(parseInt(i / 6)-1)           
  • Related