角度动态模板渲染,如ui网格单元模板(在父级的colDefs中声明的模板)

问题描述 投票:2回答:2

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;
  });

 }

}

数据table.component.ts

export class DataTableComponent implements OnInit {
@Input() gridOptions: any = [];
  constructor() { } 

  ngOnInit() {}
}

数据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 DEMO

angular typescript ui-grid ng-template dynamicgridview
2个回答
3
投票

查看我为您创建的StackBlitz演示。它利用渲染功能cellFn,您可以根据需要自定义模板。还要注意safeHtml管道在模板中渲染html的用法。

编辑:正如OP在评论中所述,他也想在模板中使用Angular指令等。所以这是用于此目的的StackBlitz演示。


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'},

我希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.