Search code examples
angularangular-flex-layout

How to use array to populate contents of the Flex Layout within for loop in angular 7


I have used Flex Layout to display a set of cards like the below screenshot. Here the Header of all the cards are "abc". But I would like to display different headers(like "abc" for first card, "def" for the second...) for each cards. Kindly advice how can I populate such values for each card using for loop. Thanks in advance.

Flex Layout grids

app.component.html

<div 
   fxLayout="row wrap" 
   fxLayout.lt-sm="column" 
   fxLayoutGap="10px" 
   fxLayoutAlign="flex-start"
   style="margin-left: 5%;">

   <ng-container *ngFor="let _ of [1,2,3,4,5,6]">
      <app-card 
         fxFlex="0 1 calc(33.3% - 32px)"
         fxFlex.lt-md="0 1 calc(50% - 32px)"
         fxFlex.lt-sm="100%"
         ></app-card>
   </ng-container>

</div>

card.component.html

<mat-card>
   <div style="height: 120px;">
      <div style="text-align: center;">
         <h2>abc</h2>
      </div>
      <div style="font-size: small;">
         Content.Content.
      </div>
   </div>
</mat-card>

card.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-card',
  templateUrl: 'card.component.html',
  styles: [`
  :host {
    display: block;
    padding: 25px;
    text-overflow: ellipsis;
    word-wrap: break-word;
    overflow: hidden;
  `]
})
export class CardComponent {}

Solution

  • Pass in an @Input property to the CardComponent:

    import { Component, Input } from '@angular/core';
    
    @Component({
      selector: 'app-card',
      templateUrl: 'card.component.html',
      styles: [`
      :host {
        display: block;
        padding: 25px;
        text-overflow: ellipsis;
        word-wrap: break-word;
        overflow: hidden;
      `]
    })
    export class CardComponent {
      @Input() cardContent;
    }
    

    And then use it in the template of the CardComponent:

    <mat-card>
       <div style="height: 120px;">
          <div style="text-align: center;">
             <h2>{{ cardContent.title }}</h2>
          </div>
          <div style="font-size: small;">
             {{ cardContent.content }}
          </div>
       </div>
    </mat-card>
    

    You can then manage this content from the Parent Component:

    <div 
       fxLayout="row wrap" 
       fxLayout.lt-sm="column" 
       fxLayoutGap="10px" 
       fxLayoutAlign="flex-start"
       style="margin-left: 5%;">
    
       <ng-container *ngFor="let content of contents">
          <app-card 
             fxFlex="0 1 calc(33.3% - 32px)"
             fxFlex.lt-md="0 1 calc(50% - 32px)"
             fxFlex.lt-sm="100%"
             [cardContent]="content"
             ></app-card>
       </ng-container>
    
    </div>
    

    You'll now have to manage a property named contents of type Array on the Parent Component now:

    contents = [{ title: 'abc', content: 'lorem ipsum...' }, {...}, {...}]