You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中使用Ant Design实现动态网格视图?

实现NG-ZORRO卡片子组件父传值+动态网格布局

你可以按照以下步骤实现:

1. 定义子组件,接收父组件传入的卡片参数

首先在子组件的TS文件中声明输入属性:

// card-item.component.ts
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-card-item',
  templateUrl: './card-item.component.html',
  styleUrls: ['./card-item.component.less']
})
export class CardItemComponent {
  // 接收父组件传入的卡片标题
  @Input() cardTitle!: string;
  // 接收父组件传入的卡片封面图地址
  @Input() cardImg!: string;
  // 接收父组件传入的卡片描述
  @Input() cardDesc!: string;
}

然后在子组件的HTML模板中绑定nz-card的对应属性:

<!-- card-item.component.html -->
<nz-card [nzTitle]="cardTitle" nzHoverable>
  <img alt="卡片封面" [src]="cardImg" style="width: 100%; margin-bottom: 16px;">
  <p>{{ cardDesc }}</p>
</nz-card>

你提到的卡片效果参考图如下:
卡片效果图

2. 父组件中调用子组件生成动态网格

首先在父组件的TS文件中定义卡片数据源:

// parent.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.less']
})
export class ParentComponent {
  // 动态卡片数据源,可根据业务需求动态增删改
  cardList = [
    {
      title: '卡片1',
      img: 'https://xxx.com/1.png',
      desc: '这是卡片1的描述内容'
    },
    {
      title: '卡片2',
      img: 'https://xxx.com/2.png',
      desc: '这是卡片2的描述内容'
    },
    // 更多卡片数据...
  ]
}

然后在父组件的HTML模板中用栅格系统实现自适应网格,循环渲染子组件:

<!-- parent.component.html -->
<!-- 用nz-row实现网格行,nzGutter设置卡片之间的间距 -->
<nz-row [nzGutter]="[16, 16]">
  <!-- 循环渲染卡片,nzCol设置响应式宽度:小屏一行2个,中屏一行3个,大屏一行4个 -->
  <nz-col [nzXs]="24" [nzSm]="12" [nzMd]="8" [nzLg]="6" *ngFor="let card of cardList">
    <!-- 传入子组件需要的参数 -->
    <app-card-item 
      [cardTitle]="card.title"
      [cardImg]="card.img"
      [cardDesc]="card.desc"
    ></app-card-item>
  </nz-col>
</nz-row>

补充说明

  • 如果不需要使用NG-ZORRO的栅格,也可以用CSS Grid实现网格布局,逻辑一致,只需要修改父组件的HTML和样式即可
  • 如果需要给卡片新增其他自定义内容,直接在子组件中新增对应的@Input()属性接收参数即可

内容的提问来源于stack exchange,提问作者tarun92

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 20:06:02