首页 > 解决方案 > 如何根据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 的强大功能。但我是角度新手,所以我找不到一个好的解决方案。

标签: htmlangulartypescript

解决方案


我想,我有一个解决方案给你。您可以使用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。


推荐阅读