Angular (7) 动态模板(ng-template)渲染类似ui grid cell template(template declared in colDefs of parent); 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>
最佳答案
查看 StackBlitz我为您创建的演示。它利用渲染函数 cellFn
,您可以在其中根据需要自定义模板。还要注意使用 safeHtml
管道在模板中呈现 html。
编辑:正如 OP 在评论中所述,他还想在模板中使用 Angular 指令等。所以这里是 StackBlitz用于此目的的演示。
关于Angular 动态模板渲染,如 ui 网格单元格模板(在 parent 的 colDefs 中声明的模板),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54685740/