Angular 2:* ngFor指令列表

时间:2016-02-18 15:57:27

标签: angularjs angular angular2-directives

我有一个Queue,它本身就有一组People。在Queue中,我想显示person模板中定义的每个Person。

queue.ts

import {Component} from 'angular2/core';
import {Person} from '../person/person';
@Component({
    selector: 'queue',
    directives: [Person],
    template: `<div class="queue">
        <person *ngFor="#tP of people"></person>
    </div>`
})
export class Queue {
    people = [];
    constructor(){
        this.addPerson(new Person("Bob",20));
        this.addPerson(new Person("Jane",30));
        this.addPerson(new Person("Dog",40));
        this.addPerson(new Person("Cat",50));

    };
    addPerson(tP:Person):void
    {
        this.people.push(tP);
    }
}

person.ts

import {Component} from 'angular2/core';

@Component({
    selector: 'person',
    template: `<div class="person">
        <div class="name">{{name}}</div>
        <div class="age">{{age}}</div>
    </div>`
})
export class Person {
    constructor(public name:string = "", public age:number = 5){};
    setName(newName:string):void{
        this.name = newName;
    }
}

我希望

<div class="queue">
<div class="person"><div class="name">Bob</div><div class="age">20</div></div>
<div class="person"><div class="name">Jane</div><div class="age">30</div></div>
<div class="person"><div class="name">Dog</div><div class="age">40</div></div>
<div class="person"><div class="name">Cat</div><div class="age">50</div></div>
</div>

我得到了什么

EXCEPTION:没有String的提供者! [人物 - &gt;字符串)[队列中的人物@ 1:16]

摘要

我想使用指令本身定义的模板来呈现指令列表。

1 个答案:

答案 0 :(得分:2)

<person *ngFor="let tP of people"></person>

已为people中的每个项目创建新人。相反,您应该只将数据添加到people = [];,然后使用绑定将数据传递到组件中。

constructor(){
    this.addPerson({name: "Bob", age: 20});
    this.addPerson({name: "Jane", age: 30});
    this.addPerson({name: "Dog", age: 40});
    this.addPerson({name: "Cat", age: 50});

};
<person *ngFor="let tP of people" [name]="tp.name" [age]="tp.age"></person>
export class Person {
  @Input() name:string;
  @Input() age:number;

  ngOnInit() {
    console.log('name: ' + this.name + ', age: ' + this.age);
  }
}

您通常不会自己创建组件实例,而是指示Angular为您执行此操作。

如果组件具有构造函数参数,Angular会在提供程序列表中查找它们并自行创建实例以将它们传递给构造函数。由此产生的错误消息是因为Angular没有string的提供程序。 (constructor(public name:string = "",