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

标签 angular typescript ui-grid ng-template dynamicgridview

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>

a busy cat

StackBlitz DEMO

最佳答案

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

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

关于Angular 动态模板渲染,如 ui 网格单元格模板(在 parent 的 colDefs 中声明的模板),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54685740/

相关文章:

angular - Typescript - 如何在 map 中设置对象键的值

angular - fa 图标不随 ngClass 变化

javascript - 操作对象数组时出现 TS2345 错误

typescript - 有没有办法实现 <T>(x : Promise<AsyncIterableIterator<T>>): AsyncIterableIterator<T> in TypeScript?

javascript - 减少由 ui-grid 或替代网格解决方案创建的监视

css - 100% height body 高于 100vh,由 Angular 的 router-outlet 引起

angular - 如何在不注入(inject)的情况下获取 Angular 路由器的实例?

visual-studio - 什么是 Visual Studio TypeScript 虚拟项目?如果我在外部编译,我怎样才能摆脱它呢?

javascript - ui 网格标题菜单选项

javascript - AngularJS 下拉菜单中调用函数