I making a simple component to create tables:
@Component({
selector: 'admin-table',
template: `
<table class='table table-bordered'>
<thead>
<th *ngFor='let column of columns'>
{{ column.label }}
</th>
</thead>
<tbody>
<tr *ngFor="let record of records">
<td *ngFor='let column of columns' [innerHTML]="fieldContent(column, record) | safeHtml">
</td>
</tr>
</tbody>
</table>
`,
})
export class AdminTableComponent {
@Input() columns: AdminTableColumn[];
@Input() records: {}[];
fieldContent(column: AdminTableColumn, record: {}) {
if (column.template) {
//TODO: parse the template and pass current record as argument
return column.template;
}
return record[column.field];
}
}
and other component to create a table of products using the above component
@Component({
selector: 'product-admin',
template: `
<h1>Products</h1>
<admin-table [columns]="columns" [records]="products"></admin-table>
`,
providers: [ProductService],
})
export class ProductAdminComponent implements OnInit {
products: Product[];
columns: AdminTableColumn[] = [
{
field: 'id',
label: 'SKU',
},
{
field: 'name',
label: 'Name',
template: '<strong>{{record.name}}</strong>',
}
];
}
Like you can see the AdminTableColumn
has a additional option called template
to set the value of the cell using a template. But I can't do this when try to render the value I got {{record.name}}
instead of the real product name.
I need parse the value entered in the template
option to allow the use of angular declarations like: {{record.name}}
or <some-component [title]="record.name"></some-component
> in order to create a rich table.
in other words, exists something like render(template, { record: record })
I'm pretty sure Angular sanitizes the html injected through innerHtml so your string interpolation will not work there.
Instead you can try parsing the template in the fieldContent function and adding the records's keys directly.
Here is an example that uses a regexp to replace all instances of {{record[key]}}, whatever the key may be, and returning the interpolated string to be injected into your Html.
You can build special directive for this purpose:
AdminComponent
Plunker Example
See also