html - 如何根据ngFor在Angular中的索引值将组件添加到不同的div?
问题描述
我写了这样一个代码来解释我的问题。
<ng-container *ngFor="let product of products | async; index as i">
<app-product-card [product]="product"></app-product-card>
</ng-container>
<div class="row">
<!--Grid column-->
<div id="gridColumn1" class="col-lg-4 col-md-12 mb-4">
<!-- if (i%3 == 0) -->
</div>
<!--Grid column-->
<!--Grid column-->
<div id="gridColumn2" class="col-lg-4 col-md-6 mb-4">
<!-- if (i%3 == 1) -->
</div>
<!--Grid column-->
<!--Grid column-->
<div id="gridColumn3" class="col-lg-4 col-md-6 mb-4">
<!-- if (i%3 == 2) -->
</div>
<!--Grid column-->
</div>
<!--Grid row-->
我ngFor
正在为每个产品创建一张卡片。
我想做的事; 如果i%3 == 0
将产品卡添加到gridColum1
,如果是 1 将其添加到gridColum2
,如果是 2 将其添加到gridColum3
。我怎样才能做到这一点?
我可以按索引对产品数组进行分组并将其作为二维数组返回,但我不喜欢这样。可以使用 javascript 来完成,但在这里我想利用 angular 的强大功能。但我是角度新手,所以我找不到一个好的解决方案。
解决方案
我想,我有一个解决方案给你。您可以使用ngIf
. 下面是我的代码和 stackblitz 链接 => Demo Stackblitz Link
。
子 HTML:
<div class="row">
<div *ngIf='index%3==0' id="gridColumn1" class="col-lg-4 col-md-12 mb-4" style="background:red">gridColumn1
</div>
<div *ngIf='index%3==1' id="gridColumn2" class="col-lg-4 col-md-6 mb-4" style="background:blue">gridColumn2
</div>
<div *ngIf='index%3==2' id="gridColumn3" class="col-lg-4 col-md-6 mb-4" style="background:green" >gridColumn3
</div>
</div>
儿童 TS:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-product-card',
templateUrl: './app-product-card.component.html',
styleUrls: ['./app-product-card.component.css']
})
export class AppProductCardComponent {
@Input() index:number;
@Input() product:any;
}
父 HTML:
<ng-container *ngFor="let product of products; index as i">
<app-product-card [product]="product" [index]="i"></app-product-card>
</ng-container>
家长 TS:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
products=[];
constructor(){
for(let i=0;i<3;i++){
let temp=new Product();
temp.pCode="PC-"+i.toString();
temp.pName="PN-"+i.toString();
this.products.push(temp);
}
}
}
export class Product{
pName:string;
pCode:string
}
注意:我已添加style=background
以检查显示的是哪个 div。
推荐阅读
- jquery - 离开组件时如何“重置”CSS更改?
- excel - 如何在 VBA 代码中写引号?
- python - 使用 Python 修复 HTML 字符串中的左括号问题
- odoo - 如何在odoo 11中使按钮不可见
- dialogflow-es - 如何获取用户在电报聊天机器人中共享的对话流侧电话号码
- c# - Systemd 服务在作为服务启动时使用我的 CPU 的 100%,如果我在没有 systemd 的情况下启动它则不会
- python - 为什么在我的猜谜游戏中数字返回高或低不正确
- python - 概括使用 numpy.meshgrid
- python - 所有 v4 请求都给出错误代码 403(禁止)
- javascript - 是否可以使用 HTML、CSS 和 Javascript 来创建可以访问 Iphone 蓝牙配对的 Iphone 应用程序?