使用* ngFor自定义模板渲染

时间:2016-07-24 13:47:24

标签: angular ngfor

我有一个历史记录组件,其中包含HistoryEntries的数组。

HistoryComponent看起来像:

 @Component({
 selector: 'history',
 template: `
    <div>         
       <historyEntry *ngFor='let entry of historyentries'></historyEntry>
    </div> `,
    directives : [HistoryEntryComponent]
 })

HistoryComponent-class看起来像:

export class HistoryComponent{
   public historyentries = [
                    new HistoryEntryComponent(1, "lalala"),
                    new HistoryEntryComponent(2, "xxxxx")
                    ];
}

然后我有一个HistoryEntryComponent:

@Component({
  selector: 'historyentry',
  template: `
    <div>
        <h1>ID: {{Id}} , Descr.: {{Description}}</h1>
    </div>
`
})

和一个班级:

export class HistoryEntryComponent {
   constructor(public Id : Number, public Description : string)
   {}
}

如果我表现出来,那就出现了。我已经使用<li>来显示id和description,它的工作方式与预期的一样。但当然HistoryEntry本身可能变得非常复杂,需要自己的逻辑等等。所以必须有一种方法来呈现模板给出的<historyentry>,不是吗?

在WPF中我会说HistoryEntryUserControl,附加了自己的ViewModel

2 个答案:

答案 0 :(得分:2)

@Component({
 selector: 'history',
 template: `
    <div>         
       <historyentry *ngFor='let entry of historyentries' [entry]="entry"></historyentry>
    </div> `,
    directives : [HistoryEntryComponent]
})
export class HistoryEntryComponent {
   @Input() entry:HistoryEntry; // or whatever type `entry` is
   constructor()
   {}
}
<h1>ID: {{entry?.Id}} , Descr.: {{entry?.Description}}</h1>

答案 1 :(得分:0)

您需要提供id和description作为historyendcomponent的输入

<historyEntry *ngFor='let entry of historyentries' [id]="entry.id" [description]="entry.description"></historyEntry>

export class HistoryEntryComponent {
   @Input id:number;
   @Inpur description:string;
   constructor(public Id : Number, public Description : string)
   {}
}