类似于ui网格单元模板(在父对象的colDefs中声明的模板)的角(7)动态模板(ng-template)渲染;自30天内以来,我以多种方式尝试过,观看了ng-template渲染视频,文章,但找不到任何解决方案,请在这里为我提供帮助。
预先感谢:)
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>
答案 0 :(得分:3)
查看我为您创建的StackBlitz演示。它利用了渲染功能cellFn
,您可以在其中随意自定义模板。还要注意使用safeHtml
管道在模板内呈现html。
编辑:如OP在注释中所述,他还希望在模板中使用Angular指令等。因此,这是StackBlitz演示示例。
答案 1 :(得分:1)
据我所知,DataTables不支持任何Angular魔术。 我使用了DataTables为您提供的呈现功能解决了类似的问题:https://datatables.net/reference/option/columns.render#function
例如,您需要更改行:
{name:'email', displayName:'Email', cellTemplate:'{{row[col.name]}}'},
收件人:
{name:'email', displayName:'Email', render:(data, type, row, meta) => 'contact ' + row.name + ' via E-Mail'},
我希望这会有所帮助。