如何在 angular 7 中的 for 循环中使用数组填充 Flex 布局的内容

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

我使用 Flex Layout 来显示一组卡片,如下图所示。这里所有牌的 Header 是 "abc"。但我想为每张卡片显示不同的 headers(如第一张卡片的 "abc",第二张卡片的 "def"...)。请建议我如何使用 for 循环为每张卡片填充这些值。提前致谢。

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 {}

@Input 属性 传递给 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;
}

然后在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>

然后您可以从父组件管理此内容:

<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>

您现在必须在父组件上管理一个名为 contents 的数组类型 属性:

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