Angular2 modulus functionality to create rows of elements

耗尽温柔 提交于 2019-12-24 00:38:47

问题


I am having trouble recreating and imagining how to recreate the following piece of vanilla Javascript code in Angular2 (I just typed it out on the spot so don't worry about syntax or logic errors). As you can see, I am looping through an array of products and if the iteration modulus of 4 then I close the div with class 'row' and start a new div with a class of row. This is so I can add 'col-xs-3 col-sm-3 col-md-3 col-lg-3' classes onto the products to make them responsive.

<div class='row'>
    <script>
        var html = '';
        for(let i = 0; i < products.length; i++) {
            html += '<div class=`product`>dom code in hhere</div>';
            if(i % 4 === 0) {
                html += '</div><div class=`row`>'
            }
        }
    </script>
<div>

This is easy enough to do in Vanilla and jQuery but in Angular I believe you cannot have an if clause not on an element so I cannot close the row div and start a new one. Here is my code so far:

<div class='row'>
        <div *ngFor='let product of products; let i = index' class='col-xs-1 col-sm-2 col-md-3 col-lg-3'>
            <div class='product'>
                <div class='image'>
                    <img [src]="product.image" />
                </div>
                <div class='info'>
                    <h4 class='title'>{{ product.name }}</h4>
                </div>
            </div>
        </div>
    </div>

So, as you can see, I want to close off the parent '' element on every fourth product and start a new row. I have thought about using a pipe but I still couldn't think of how to utilise this properly.

Can anyone help me here? Thanks


回答1:


I'll expand on my comment, it is really easy, you should manipulate the data before sending it to the template:

groupProductList() {
  for(let i = 1; i < 100; i = i + 4) {
    let group = this.productList.slice(i, i + 4);
    this.productListGrouped.push(group);
  }

Then in the template:

<div class="row" *ngFor="let group of productListGrouped; let i = index">
  <div class="col" *ngFor="let product of productListGrouped[i]">
    {{ product.id }}
    {{ product.name }}
  </div>
</div>

Se working Plunkr.



来源:https://stackoverflow.com/questions/42095567/angular2-modulus-functionality-to-create-rows-of-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!