I have a dynamic table. The columns and their formatting are described in a separate structure. I want to format the content of the cell depending on the value with a directive. The directive to use can be specified with the "formatter".
Type definitions:
export interface Table extends BaseItem {
columns: Array<TableColumn>;
data: Array<TableRow>;
}
export interface TableColumn {
id: string;
label?: string; // header
type: ColumnType;
formatter?: string; // special formatter (e.g. valueAsIcon )
}
The data in the table object:
{
id: "diagnosticlist",
type: "table",
columns: [
{
id: "id",
label: "Id",
},
{
id: "status",
label: "Status",
formatter: "formatNamur",
},
{
id: "remedy",
label: "Remedy",
type: "button",
formatter: "formatShowRemedy",
},
],
data: [
{
id: 0,
status: "F",
},
{
id: 1,
status: "C",
},
{
id: 2,
status: "S",
},
{
id: 3,
status: "M",
remedy: "Hello",
},
]
}
The directive should be inserted dynamically in the HTML code. Here [{{column.formatter}}]
<table mat-table matSort TableResponsive [dataSource]="dataSource">
<ng-container *ngFor="let column of table?.columns?? []">
<ng-container matColumnDef="{{column.id}}">
<th mat-header-cell *matHeaderCellDef>{{column.label}}</th>
<td mat-cell *matCellDef="let row" [{{column.formatter}}]="">
{{row[column.id]}}
</td>
</ng-container>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
The code of the directive
import { Directive, ElementRef, HostBinding, Input } from '@angular/core';
@Directive({
selector: '[formatNamur]'
})
export class NamurDirective {
@HostBinding('style.backgroundColor') bgColor : string;
constructor() {
this.bgColor = 'yellow';
}
}
- How can I specify the directive directly in the HTML?
- How can I pass the content of the cell to this directive?