【发布时间】:2019-07-08 04:54:42
【问题描述】:
Angular(7)动态模板(ng-template)渲染类似ui网格单元模板(模板在父级colDefs中声明); 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>
【问题讨论】:
-
为什么不将cellTemplate添加到模板中并添加条件,而不是在ts文件中定义呢?
-
它应该适用于任何时间的 cellTemplate,适用于任何类型的 json,如 ui 网格,我必须不断为 diff json 服务添加条件,这里的 data-table 组件应该普通
标签: angular typescript ui-grid ng-template dynamicgridview