Home > Software design >  *ngFor on different divs in Angular
*ngFor on different divs in Angular

Time:08-10

I have markup in an angular project that looks like this.

<div  *ngFor="let popular of populars">
    <img  src={{popular.imageArticle}} alt="img1">
    <h3>{{ popular.title }}</h3>
    <p>{{ popular.caption }}</p>      
    <div >
        <img  src={{popular.imageUser}} alt="user">
        <a  href="">{{ popular.nameUser }}</a>
        <ul >
            <img  src="assets/img/Vector.svg" alt="kudos">
            <li >{{popular.kudos}}</li>
            <img  src="assets/img/star.svg" alt="star">
        </ul>
    </div>                        
</div>

Style class smallCard looks like this:

.smallCard{   
    display: flex;
    flex-direction: column;
    min-height:0;
    margin: 0 20px 20px 0 ;
    max-width: 310px;
    box-shadow: 0px 2px 8px rgba(0, 0, 0, 0.15);
    background: #FFFFFF;
} 

And I have an array of elements like this:

 export const populars = [ {
  id: 1,
  title: 'How To Add Confidence Intervals to Any Model',
  caption: 'I would like to add another technique to your toolkit — confidence intervals',
  kudos: 147,
  imageUser: 'assets/img/folkman.png',
  nameUser: 'Tyler Folkman',
  imageArticle: 'assets/img/Image.png',
},
{
  id: 2,
  title: 'What’s New in JavaScript — ES2019',
  kudos: 120,
  imageUser: 'assets/img/folkman.png',
  nameUser: 'Tyler Folkman',
  imageArticle: 'assets/img/ImageSmall2.png',
},
{
  id: 3,
  title: 'How To Fake Being a Good Programmer',
  kudos: 89,
  imageUser: 'assets/img/folkman.png',
  nameUser: 'Tyler Folkman',
  imageArticle: 'assets/img/ImageSmall3.png',
},
{
  id: 4,
  title: 'Reduce Memory Usage and Make Your Python Code Faster Using Generators',
  kudos: 21,
  imageUser: 'assets/img/folkman.png',
  nameUser: 'Tyler Folkman',
  imageArticle: 'assets/img/ImageSmall4.png',
},
{
  id: 5,
  title: 'Here Are 11 Console Commands Every Developer Should Know',
  kudos: 3,
  imageUser: 'assets/img/folkman.png',
  nameUser: 'Tyler Folkman',
  imageArticle: 'assets/img/ImageSmall5.png',
}
]

I want to loop through this array and fill output one element in a 540px long div and the rest of the elements in a 260px long div. How to do it with *ngFor directive correctly? Layout on the picture.

enter image description here

CodePudding user response:

You can use first local variable of *ngFor directive

*ngFor="let popular of populars; let first = first;"

And then use ngClass to apply bigCard and smallCard class on div conditionally. This makes sure it applies to only first elemenent.

[ngClass]="first? 'bigCard': 'smallCard'"

HTML

Everything compiled together would look like below.

<div 
  [ngClass]="first? 'bigCard': 'smallCard'"
  *ngFor="let popular of populars">
  ....
</div>
  • Related