2016-07-24 89 views
1

我有一个历史组件,其中包含HistoryEntries的数组。自定义模板渲染与* ngFor

HistoryComponent样子:

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

的HistoryComponent级的样子:

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) 
    {} 
} 

如果我渲染,nothings出现。我已经使用<li>来显示编号和说明,其工作方式与预期相同。但当然HistoryEntry本身可能会变得非常复杂,并且需要自己的逻辑等等。所以必须有一种方法来模拟<historyentry>,不是吗?

在WPF中,我会说HistoryEntry是一个UserControl与它自己的ViewModel附加。

回答

1
@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> 
+0

我收到“无法绑定到'条目,因为它不是已知的本地属性”。 “入口”的类型将是“HistoryEntryComponent”,因为这就是ngFor迭代。虽然我喜欢这个解决方案比单独设置“Id”和“Description”要好得多,但它仍然很奇怪。我们告诉Angular,我们需要渲染元素和迭代历史记录为什么我们必须手动将迭代值设置为historyentry元素? –

+0

仅仅因为'* ngFor'在''元素上,并不意味着数据必须与''相关。标签必须是''而不是''或将选择器从'historyentry'更改为'historyEntry'。我从你的问题中复制了这个错误。 –

0

您需要提供ID和说明作为输入提供给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) 
    {} 
} 
+0

时不会编译。这很奇怪。但我也不明白这个解决方案。 ngFor历史入口的迭代。那么,为什么我必须再次设置属性?私人会员怎么样? –