Angular (7) dynamic template (ng-template) rendering like ui grid cell template (template declared in colDefs of parent); I tried in so many ways since more than 30 days, watched ng-template rendering videos, articles, but could'not find any solution, kindly help me here.
Thanks in advance :)
app.component.ts
export class AppComponent implements OnInit {
name = 'Angular';
gridOptions:any;
constructor(private http: HttpClient){}
ngOnInit(){
this.gridOptions = {
colDefs:[
{name:'id', displayName:'ID',width:80},
{name:'name', displayName:'Name'},
{name:'username', displayName:'Username', cellTemplate:'Static text from template'},
{name:'email', displayName:'Email', cellTemplate:'{{row[col.name]}}'}, // i tried like this
{name:'phone', displayName:'phone', cellTemplate:"<strong style='color:blue'> + row[col.name] + </strong>"}, // I need to achive this kind of template like ui grid for angularjs
{name:'website', displayName:'website', cellTemplate:'row[col.name]'}, // i tried like this also
]
}
this.http.get("https://jsonplaceholder.typicode.com/users").subscribe((res) =>{
this.gridOptions.data = res;
});
}
}
data-table.component.ts
export class DataTableComponent implements OnInit {
@Input() gridOptions: any = [];
constructor() { }
ngOnInit() {}
}
data-table.component.html
<table>
<tr>
<th *ngFor="let col of gridOptions.colDefs">{{col.name}}</th>
</tr>
<tr *ngFor="let row of gridOptions.data ;let i = index">
<td *ngFor="let col of gridOptions.colDefs">
<ng-container *ngIf="!col.cellTemplate else myTemplate" [ngTemplateOutlet]="myTemplate">
{{row[col.name]}}
</ng-container>
<ng-template #myTemplate row="row" col="col">
{{col.cellTemplate}}
</ng-template>
<!-- <ng-template #myTemplate row="row" col="col" innerHTML="col.cellTemplate}"></ng-template> -->
</td>
</tr>
</table>
app.component.html
<app-data-table [gridOptions]="gridOptions"></app-data-table>
Check out StackBlitz demo that I created for you. It's leverage the render function cellFn
in which you can customize template as you please. Also notice the usage of safeHtml
pipe to render html inside template.
EDIT: As the OP stated in comments, he also wants to use Angular directives etc. in template. So here is the StackBlitz demo for this purpose.