2017-10-04 63 views
0

我有一个数组如下:绘制表与正确的for循环

public products: any = [ 
{title: 'Product_1', desc: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry', img: '../assets/prod_1.jpg', property_1: 50, property_2: 6, property_3: 0, property_4: 76, property_5: 54, property_6: 87, property_7: 0}, 
{title: 'Product_2', desc: 'Lorem Ipsum has been the industrys standard dummy text ever since the 1500s', img: '../assets/prod_2.jpg', property_1: 0, property_2: 0, property_3: 65, property_4: 0, property_5: 0, property_6: 7, property_7: 88}, 
{title: 'Product_3', desc: 'It has survived not only five centuries but also the leap into electronic typesetting', img: '../assets/prod_3.jpg', property_1: 0, property_2: 97, property_3: 0, property_4: 56, property_5: 0, property_6: 0, property_7: 86}, 
{title: 'Product_4', desc: ' It was popularised in the 1960s with the release of Letraset sheets containing,', img: '../assets/prod_4.jpg', property_1: 90, property_2: 25, property_3: 56, property_4: 64, property_5: 0, property_6: 98, property_7: 0}, 
] 

,我试图从它呈现表如下:

<table> 
    <ng-template let-product ngFor [ngForOf]="products"> 

    <td> 
     <h5>{{product.title}}</h5> 
     <img src="{{product.img}}" height="200" width="300" border="1"> 
     <h6>{{product.desc}}</h6> 
    </td> 

    </ng-template> 
</table> 

但是这工作,这不是如何我想要它。我想它显示为以下几点:

enter image description here

我怎么能写我的ngFor循环,以实现这一目标?

+0

您的密钥的数量是动态的? – Wandrille

回答

1

你可以试试:

<table *ngIf="keyList && products"> 
    <ng-template let-product ngFor [ngForOf]="products"> 
    <td> 
     <h5>{{product.title}}</h5> 
     <img src="{{product.img}}" height="200" width="300" border="1"> 
     <h6>{{product.desc}}</h6> 
    </td> 
    </ng-template> 
    <ng-container *ngFor="let key of keyList" > 
    <tr> 
    <td *ngFor="let item of products"> 
     {{item[key]}} 
    </td> 
    </tr> 
</ng-container> 
</table> 

有:

this.keyList= Object.keys(this.products[0]) 
this.keyList.splice(this.keyList.indexOf('title'),1) 
this.keyList.splice(this.keyList.indexOf('desc'),1) 
this.keyList.splice(this.keyList.indexOf('img'),1) 
+0

使用const键抛出一个错误,因为ngFor不是td的已知属性,如果我用let替换它,那么基本上什么都不会呈现 – Nitish

+0

感谢你的方法,但我想到了如何进一步去解决它。此外,使用const甚至会从更新的答案中引发错误。所以就用让和' ​​

性质1
{{item.property_1}} ' – Nitish

+0

https://embed.plnkr.co/yditsYYiacAFy8Keu155/ 但是,如果列表中的第一项与其他行相比键数少于其他键,则其他键将错过 – Wandrille