Angular2 @ TypeScript嵌套* ngFor没有嵌套对象

时间:2016-03-09 11:32:00

标签: typescript angular

我使用的是Angular 2.0.0-beta.0和TypeScript 1.7.5

如何完成以下输出而不将任何内容更改为resources结构:

factory
 - metal 
 - plastic
hardware store
 - shovel
 - ladder

代码:

import {bootstrap}         from 'angular2/platform/browser';
import {Component}         from 'angular2/core';

@Component({
    selector: 'my-app',
    template: `
        <div *ngFor="#resource of resources">
            <h3>{{resource.group}}</h3>
            <ul>
                <li *ngFor="#resource of resources">{{resource.name}}</li>
            </ul>
        </div>
    `
})

export class Test {

    private resources = [
        {name: "metal", group: "factory"},
        {name: "plastic", group: "factory"},
        {name: "shovel", group: "hardware store"},
        {name: "ladder", group: "hardware store"}
    ];

    constructor () {}
}

bootstrap(Test);

2 个答案:

答案 0 :(得分:4)

我会为此创建一个管道:

@Pipe({name: 'groups'})
export class GroupsPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    var groups = {};
    value.forEach(function(o) {
      var group = o.group;
      groups[group] = groups[group] ?
         groups[group] : { name: group, resources: [] };
      groups[group].resources.push(o);  
    });

    return Object.keys(groups).map(function (key) {return groups[key]});
  }
}

然后,您可以按照以下说明更新模板:

<div *ngFor="#group of resources | groups">
  <h3>{{group.name}}</h3>
  <ul>
    <li *ngFor="#resource of group.resources">{{resource.name}}</li>
  </ul>
</div>

请参阅此plunkr:https://plnkr.co/edit/gzLERn?p=preview

答案 1 :(得分:0)

我接受了@ThierryTemplier的完美答案,并使其更加通用,因此溶剂可用于不同的物体阵列:

import {bootstrap}          from 'angular2/platform/browser';
import {Component, Pipe}    from 'angular2/core';

@Pipe({name: 'makeHeader'})

export class makeHeaderPipe {
    transform(value: any, args: string[]): any {
        var newObject = {};
        value.forEach(element => {
            var header = element[args[1]];
            if (!newObject[header]) {
                newObject[header] = { name: header };
                newObject[header][args[0]] = [];
            }
            newObject[header][args[0]].push(element);
        });
        return Object.keys(newObject).map(key => {return newObject[key]});
    }
}

@Component({
    selector: 'my-app',
    template: `
    <div *ngFor="#header of students | makeHeader:'students':'teacher'">
      <h3>{{header.name}}</h3>
      <ul>
        <li *ngFor="#student of header.students">{{student.name}}</li>
      </ul>
    </div>
  `,
    pipes: [makeHeaderPipe]
})

export class Test {

    private students = [
        {name: "Gerard", teacher: "Lars"},
        {name: "Murphy", teacher: "Rachel"},
        {name: "Lauren", teacher: "Lars"},
        {name: "Stevie", teacher: "Rachel"}
    ];

    constructor () {}
}

bootstrap(Test);