使用 *ngFor 自定义模板渲染

Sve*_*dos 5 ngfor angular

我有一个 History 组件,其中包含一个HistoryEntries.

HistoryComponent 好像:

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

HistoryComponent 类看起来像:

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

然后我有一个 HistoryEntryComponent:

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

和一个班级:

export class HistoryEntryComponent {
   constructor(public Id : Number, public Description : string)
   {}
}
Run Code Online (Sandbox Code Playgroud)

如果我渲染它,什么都没有出现。我已经使用 a<li>来显示 id 和描述,它的工作原理与预期一致。但是当然HistoryEntry它本身可能会变得非常复杂并且需要它自己的逻辑等等。所以必须有一种方法可以<historyentry>按照模板给出的方式进行渲染,不是吗?

在 WPF 中,我会说HistoryEntry是一个UserControl带有它自己的ViewModel附件。

Gün*_*uer 5

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