Reputation: 887
I'm trying to build a table component (with standard features) where rows should be defined as a template.
At the moment I've tried this way (code simplified):
1) parent component
@Component({
selector: 'simple-grid',
template: `<table><tbody>
<ng-container *ngFor="let item of items; let i = index">
<template
[ngTemplateOutlet]="template"
[ngOutletContext]="{'item': item, 'i': i}">
</template>
</ng-container>
</tbody></table>
`
})
export class SimpleGridComponent {
@Input()
items: any[] = [];
@ContentChild(TemplateRef)
template: any;
}
2) usage:
@Component({
selector: 'simple-grid',
template: `
<simple-grid [items]="users" >
<template>
<tr [class.even]="i%2==0" [class.odd]="i%2!=0">
item: {{item?.id}} {{ someProperty }} {{id}}
</tr>
</template>
</simple-grid>`
})
MyPage{
public users: Users = [{id: 1, name='one'}, {id: 2, name='two' }];
public someProperty: string = 'dummy';
}
Result:
<table>
<tbody>
<tr>
item: dummy
</tr>
<tr>
item: dummy
</tr>
<tbody>
</table>
so:
Template is used
Rows are correctly repeated
but I'm not able to show item properties; rows are not bound to the "item" in the *ngFor, but the MyPage itself. ps: if I select a row with Augury, in console $a.context contains correctly the item and the index.
How can I solve this problem?
Upvotes: 0
Views: 1073
Reputation: 887
I've found that template syntax needs "let-" attribute to use items available in the context of the template.
So, I've fixed the code in this way:
@Component({
selector: 'simple-grid',
template: `
<simple-grid [items]="users" >
<template let-item="item" let-index="i">
<tr [class.even]="index%2==0" [class.odd]="index%2!=0">
item: {{item?.id}} {{ someProperty }} {{id}}
</tr>
</template>
</simple-grid>`
})
MyPage{
public users: Users = [{id: 1, name='one'}, {id: 2, name='two' }];
}
example in plunker: https://plnkr.co/edit/PwSpjy4KTYjstGWTWP24?p=preview
Upvotes: 1