简体   繁体   English

Angular2 ng为了保存变量,迁移Twig

[英]Angular2 ngFor saving variable, migrating Twig

I'm converting some PHP Twig templates into a new Angular5 project, and I'm stuck on how to handle a simple loop. 我正在将一些PHP Twig模板转换为新的Angular5项目,而我仍然坚持如何处理简单的循环。

In my original Twig template, I have a series of data I loop through that includes a Month column. 在我最初的Twig模板中,我循环浏览了一系列数据,其中包括“月”列。 The data is already sorted by month, and I use this to create a header for each month in the loop by saving the variable, like: 数据已经按月排序,我使用它通过保存变量来为循环中的每个月创建标题,例如:

{% set savedMonth = '' %}
{% for result in results %}
    {% set thisMonth = result.month %}
    {% if savedMonth != thisMonth %}
        <tr bgcolor='#c0c0c0'>
            <td colspan='5' align='left'>{{ thisMonth }}</td>
        </tr>
        {% set savedMonth = thisMonth %}
    {% endif %}
    <tr>
        <td valign='top' align='left'><a href='{{ path("app_view_index", { 'id': doc.id }) }}'>{{ doc.id }}</a></td>

    </tr>
{% endfor %}

This is a simplified example but you can see we look for a field change so I can insert my color row with the month at the start of each change. 这是一个简化的示例,但是您可以看到我们正在寻找字段更改,因此我可以在每次更改开始时插入带有月份的颜色行。

Now I'm attempting to do the same thing in Angular5, but I can't figure out how to loop with *ngFor and do this kind of save. 现在,我试图在Angular5中执行相同的操作,但是我不知道如何使用* ngFor进行循环并进行这种保存。 Is it even possible? 可能吗?

<tr *ngFor="let result of searchResults">
  <td align="left" class="home"><a [routerLink]="['/view', result.id]">{{ result.id }}</a></td>
  <td align="left" class="home">Subjects here</td> 
</tr>

Actually after some playing around I got a working version 实际上,经过一番游戏之后,我得到了一个有效的版本

in .ts 在.ts中

savedMonth: string;

changedMonth(month: any | string) {
 if (this.savedMonth === month) {
   return false;
  } else {
   this.savedMonth = month;
  return true;
 }
}

in template: 在模板中:

<ng-container *ngFor="let result of searchResults">
   <tr *ngIf="changedMonth(result.month)" bgcolor='#c0c0c0'>
       <td colspan='5' align='left'>{{ result.month }} </td>
    </tr>
    <tr>
       <td align="left" class="home"><a [routerLink]="['/view', result.id]">{{ result.id }}</a></td>         
    </tr>
  </ng-container>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM