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

Angular dynamic template rendering like ui grid cell template (template declared in colDefs of parent)

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

 }

}

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

据我所知,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'},

希望对您有所帮助。

查看我为您创建的 StackBlitz 演示。它利用渲染函数 cellFn,您可以在其中根据需要自定义模板。另请注意使用 safeHtml 管道在模板内呈现 html。

EDIT:正如 OP 在评论中所述,他还想在模板中使用 Angular 指令等。因此,这里是用于此目的的 StackBlitz 演示。