Angular2模数功能可创建元素行 [英] Angular2 modulus functionality to create rows of elements

查看:41
本文介绍了Angular2模数功能可创建元素行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在重新创建和想象如何在Angular2中重新创建下面的原始Javascript代码时遇到了麻烦(我只是在现场将其键入,所以不必担心语法或逻辑错误).如您所见,我正在遍历一系列产品,并且如果迭代模数为4,则将关闭类行"的div,并开始使用行类的新div.因此,我可以在产品上添加'col-xs-3 col-sm-3 col-md-3 col-lg-3'类,以使其具有响应能力.

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>

这在Vanilla和jQuery中很容易做到,但是在Angular中,我相信您不能在一个元素上没有if子句,因此我无法关闭行div并开始一个新的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>

因此,正如您所看到的,我想在每四个产品上都关闭parent元素,并开始新的一行.我曾经考虑过使用管道,但是我仍然想不出如何正确利用管道.

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

推荐答案

我将扩展我的评论,这确实很容易,您应该在将数据发送到模板之前对其进行操作:

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);
  }

然后在模板中:

<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>

正在工作 Plunkr .

这篇关于Angular2模数功能可创建元素行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆