2017-10-04 112 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